简体   繁体   中英

Angular 2 using template reference variable ngForm as input binding

I'm building a component that has an input 'valid'. If I bind the value to a member of the parent component, things work well. But if I bind it to a template reference like so

<step [valid]="name.valid">

      <input type="text" name="name"
             #name="ngForm"
             [(ngModel)]="name"
             required>

</step>

I get

Expression has changed after it was checked. Previous value: 'true'. Current value: 'false'

which I partly understand. I get that the ngForm valid check occurs after component initialization, and therefore the value has changed. What I don't get is why this is a problem, and why this can be solved by calling enableProdMode(), and why enableProdMode() is a bad idea.

I also tried ChangeDetectorRef with .detach() and .reattach() to temporary disable change detection, which didn't solve it and sounds like a bad idea too.

Any thoughts?

That's a known issue. Use instead

<form #f="ngForm">
  <step [valid]="f.controls['name'].valid">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM