2016-04-15 78 views
13

可能有人请解释一下什么是背后的以下行为:Angular2,* ngIf和本地模板变量

说,我们有有_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:

有人能解释这是怎么回事和/或指向我这样做的正确的一条文档编制的?

在此先感谢!

编辑:

这里有一个plunker显示问题

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

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

+0

是你的_model布尔? –

+0

你可以做一个笨蛋吗? –

+0

刚刚在我的应用程序中进行了测试,我可以重现您的问题。不知何故''myInput'在添加'* ngIf'后会得到'undefined'。这感觉就像一个角度错误,或者有人必须提出一个很好的解释。 – PierreDuc

回答

31

我们可以在相同的元素引用本地模板变量的问题,在兄弟元素上或在任何子元素上。 - ref

* 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) 
    ) 
} 

查看更多Que ryList方法在API doc

+0

参见https://github.com/angular/angular/issues/6179 –