首页 文章

Angular2,* ngIf和本地模板变量

提问于
浏览
15

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

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

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

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

<br>Class: {{myInput?.className}}

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

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

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

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

双花括号插值停止工作,因为显然本地 myInput 变量即使代码中没有其他内容更改也不会被初始化,_model对象仍然在 onNgInit() 中创建,输入字段仍然正常工作 . {{myInput?.className}} 呈现的唯一内容是

Class:

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

提前致谢!

编辑:

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

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

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

1 回答

  • 33

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

    • ngIf变为/扩展为
    <template [ngIf]="_model">
        <input type="text" class="form-control" required [(ngModel)]="_model.firstName"
         ngControl="test1" #myInput>
    </template>
    

    因此,本地模板变量 #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>
    

    Plunker


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

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

    查看API doc中的更多QueryList方法 .

相关问题