如other responses所示,Angular2应用程序的初始例程应该在ngOnInit()方法中启动,使构造函数专门用于依赖注入。
但是,在我关注的Reactive Forms tutorial中,表单的初始化在构造函数中:
export class HeroDetailComponent3 {
heroForm: FormGroup; // <--- heroForm is of type FormGroup
constructor(private fb: FormBuilder) { // <--- inject FormBuilder
this.createForm();
}
createForm() {
this.heroForm = this.fb.group({
name: '', // <--- the FormControl called "name"
});
}
}
是真的有重大差异还是只是一个小问题?
在formGroup
中初始化ngOnInit()
并不是一种不好的做法,因为如果您希望使用依赖于(直接或间接)组件@Input()
s的值来初始化表单,则实际需要它。
例如:
class SignInFormComponent {
@Input() currentLogin: string;
formGroup: FormGroup;
constructor(private fb: FormBuilder) {
// this.currentLogin is not known yet here
}
ngOnInit(): void {
this.formGroup = this.fb.group({
loginEmail: [this.currentLogin, Validators.email],
loginPassword: [''],
});
}
}
我相信它是因为构造函数中的createForm方法将在ngOninit之前执行,并且您的表单将在渲染组件后立即可用。
取决于您的具体用例和设计。可能你会遇到与你的其他get
可能依赖的formControls
方法有关的问题。您可以从构造函数中创建表单中受益,并且只要呈现组件,表单就会就绪。但是,如果你需要在表格上为subscribe
做.valueChanges
到formControls
,你可能会有时间问题。你不能建立你的依赖formControls
,除非你.subscribe
,你不能.subscribe
,直到表格初始化。你可能会遇到error: cannot read property 'get' of undefined
。