Angular2,*ngIf和本地模板变量

RVP*_*RVP 16 interpolation angular

有人可以解释以下行为背后的原因:

假设我们有一个具有_model对象的Angular2组件.然后在模板中我们有这个

<form>
    <input type="text" class="form-control" required [(ngModel)]="_model.firstName" ngControl="test2"  #myInput >
    <br>Class: {{myInput?.className}}
</form>
Run Code Online (Sandbox Code Playgroud)

_model从一开始就可以在ngOnInit中从头开始创建.输入字段使用_model.firstName变量和行正确填充

_model

在模板中正确呈现以下内容

_model.

到现在为止还挺好.令我困惑的是,我添加*ngIf的那一刻,我将输入字段更改为

<input *ngIf="_model" type="text" class="form-control" required [(ngModel)]="_model.firstName" ngControl="test2"  #myInput >
Run Code Online (Sandbox Code Playgroud)

双花括号插值停止工作,因为ngOnInit()即使代码中没有其他内容发生变化,显然局部变量也不会被初始化,仍然会创建_model对象_model.firstName并且输入字段仍然正常工作.<br>Class: {{myInput?.className}}呈现的唯一的东西是

Class: form-control ng-untouched ng-pristine ng-invalid

有人可以解释发生了什么和/或指向我正确的文件吗?

提前致谢!

编辑:

这是一个能够显示问题的傻瓜

http://plnkr.co/edit/itNRpy5lc9PB837C7HdP?p=preview

创建错误报告https://github.com/angular/angular/issues/8087

Mar*_*cok 34

我们可以在同一元素,兄弟元素或任何子元素上引用本地模板变量.- 参考

*ngIf变为/扩展为

<template [ngIf]="_model">
    <input type="text" class="form-control" required [(ngModel)]="_model.firstName"
     ngControl="test1" #myInput>
</template>
Run Code Online (Sandbox Code Playgroud)

因此,本地模板变量#myInput只能在模板块内引用(即兄弟元素和/或子元素).因此,您必须在模板中放置任何想要引用本地模板变量的HTML:

<template [ngIf]="_model">
   <input type="text" class="form-control" required [(ngModel)]="_model.firstName"
    ngControl="test1"  #myInput >
   <br>Class (this works): {{myInput?.className}}
</template>
Run Code Online (Sandbox Code Playgroud)

Plunker


如果您需要在与输入相关的模板块之外显示某些内容,请使用@ViewChildren('myInput') list:QueryList<ElementRef>然后订阅更改:

ngAfterViewInit() {
   this.list.changes.subscribe( newList =>
      console.log('new list size:', newList.length)
   )
}
Run Code Online (Sandbox Code Playgroud)

查看API文档中的更多QueryList方法.