2017-04-24 31 views
5

other responses所示,Angular2應用程序的初始例程應該在ngOnInit()方法中啓動,留下專用於依賴注入的構造函數。爲什麼要在構造函數中而不是ngOnInit中創建我的Angular2反應形式?

然而,在我正在關注的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" 
    }); 
    } 
} 

是否真的有顯著差異或者是它只是一個小問題?

+0

再次打開一個公關的角度文檔項目。 –

回答

1

我相信它是因爲構造函數中的createForm方法將在ngOninit之前執行,並且您的表單將在組件呈現後儘快使用。

0

初始化在ngOnInit()formGroup是不是一個不好的做法,因爲它會如果你希望你的形式與從組件@Input()小號依賴(直接或間接)值來初始化實際需要。

例如:

class SignInFormComponent { 
    @Input() currentLogin: string; 
    formGroup: FormGroup; 

    constructor() { 
    // this.currentLogin is not known yet here 
    } 

    ngOnInit(): void { 
    this.formGroup = this._fb.group({ 
     loginEmail: [this.currentLogin, Validators.email], 
     loginPassword: [''], 
    }); 
    } 
} 
相關問題