在Angular 6中,您可以在subscribe内部使用defaultValue来设置FormGroup的初始值。以下是一个示例代码:
首先,在组件的初始化中创建一个FormGroup,并设置defaultValue作为初始值:
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent implements OnInit {
myForm: FormGroup;
ngOnInit() {
this.myForm = new FormGroup({
name: new FormControl(''),
email: new FormControl('')
});
}
}
然后,在需要订阅Observable的地方,通过subscribe方法来访问Observable中的数据,并将数据设置为FormGroup的defaultValue:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { MyService } from 'path/to/my-service';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent implements OnInit {
myForm: FormGroup;
constructor(private myService: MyService) { }
ngOnInit() {
this.myForm = new FormGroup({
name: new FormControl(''),
email: new FormControl('')
});
this.myService.getData().subscribe(data => {
// 将数据设置为FormGroup的defaultValue
this.myForm.setValue({
name: data.name,
email: data.email
});
});
}
}
在上面的代码中,myService
是一个服务,它返回一个Observable来获取数据。在subscribe内部,我们将数据设置为FormGroup的defaultValue,以便在表单中显示默认值。
请注意,使用setValue方法来设置FormGroup的值会覆盖FormGroup中的所有控件的值,因此需要确保数据的结构与FormGroup中的控件一致。
希望这可以帮助到您!