2017-10-12 24 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"