Could someone please explain what's behind the following behavior?
Say we have an Angular 2 component that has a _model object. Then in the template we have this:
<form>
<input type="text" class="form-control" required [(ngModel)]="_model.firstName" ngControl="test2" #myInput >
<br>Class: {{myInput?.className}}
</form>
The _model is available from the beginning being created from scratch in ngOnInit(). The input field is properly populated with the _model.firstName variable and the line:
<br>Class: {{myInput?.className}}
correctly renders the following in the template:
Class: form-control ng-untouched ng-pristine ng-invalid.
So far so good. What confuses me is that the moment I add *ngIf and I change the input field to
<input *ngIf="_model" type="text" class="form-control" required [(ngModel)]="_model.firstName" ngControl="test2" #myInput >
The double curly braces interpolation stops working because apparently the local myInput variable doesn't get initialized even when nothing else in the code changes, the _model object is still created in onNgInit() and the input field is still working properly. The only thing that the {{myInput?.className}} renders is
Class:
Can someone explain what's going on and/or point me to the correct piece of documentation for this?
EDIT:
Here's a Plunker that shows the issue in question.
Created bug report https://github.com/angular/angular/issues/8087
#myInputgetsundefinedafter you add*ngIf. This feels like an angular2 bug, or someone must come up with a good explanation. - Poul Kruijt@ViewChild('myInput') myInputRef : ElementRef;, andClass: {{myInputRef?.nativeElement?.className}}, but that does not feel like an appropriate approach - Poul KruijtngFordirective instead ofngIf, naming an element and using that names outside ofngForcontext will not makes sense (since there will be potentially more that one element with that name). same goes here, Consider following, element's name is available inside structural directive's context, but not outside of it. This makes sense, since Angular can't know whether specific directive will repeat his template or not. - tchelidze