2017-10-12 23 views
1

訪問由ngForm產生FormControl我有這樣的代碼在我的模板:無法從* ngIf

<form #form="ngForm" (ngSubmit)="save(form)"> 
    <input ngModel type="text" name="saveas"> 
    <button *ngIf="form.value.saveas.length > 0" type="submit">Save</button> 
</form> 

頁面加載時,我收到以下錯誤:

TypeError: Cannot read property 'length' of undefined.

但它發生只有一次,之後* ngIf按預期工作,切換提交按鈕。是什麼導致了問題?我只是試圖在Angular生成之前太早訪問FormControl?

回答

1

Template-driven forms are asynchronous

They delegate creation of their form controls to directives. To avoid "changed after checked" errors, these directives take more than one cycle to build the entire control tree. That means you must wait a tick before manipulating any of the controls

這也意味着,form.value.saveas值是在undefined第一次。所以要擺脫這個錯誤只需使用安全導航算子:

*ngIf="form.value.saveas?.length > 0"