*ngIf 和本地模板变量 [英] *ngIf and local template variables
问题描述
有人可以解释以下行为背后的原因吗?
Could someone please explain what's behind the following behavior?
假设我们有一个 Angular 2 组件,它有一个 _model
对象.然后在模板中我们有这个:
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>
_model
在 ngOnInit()
中从头开始创建.输入字段正确填充了 _model.firstName
变量和行:
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:
类:{{myInput?.className}}
在模板中正确呈现以下内容:
correctly renders the following in the template:
Class: form-control ng-untouched ng-pristine ng-invalid
.
到目前为止一切顺利.让我困惑的是,当我添加 *ngIf
并将输入字段更改为
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 >
双花括号插值停止工作,因为即使代码中没有其他任何更改,显然本地 myInput
变量也没有被初始化,_model 对象
仍然被创建在 onNgInit()
和输入字段仍然正常工作.{{myInput?.className}}
呈现的唯一内容是
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
类:
有人可以解释发生了什么和/或为此指出正确的文档吗?
Can someone explain what's going on and/or point me to the correct piece of documentation for this?
这是一个 Plunker,显示了相关问题.
Here's a Plunker that shows the issue in question.
创建错误报告 https://github.com/angular/angular/issues/8087
推荐答案
我们可以在同一个元素、同级元素或任何子元素上引用本地模板变量.-- ref
*ngIf 变为/扩展为
*ngIf becomes/expands to
<template [ngIf]="_model">
<input type="text" class="form-control" required [(ngModel)]="_model.firstName"
ngControl="test1" #myInput>
</template>
所以局部模板变量 #myInput
只能在模板块(即兄弟元素和/或子元素)内被引用.因此,您必须将任何想要引用本地模板变量的 HTML 放入模板中:
So local template variable #myInput
can only be referenced inside the template block (i.e., sibling and/or child elements). Hence you would have to put any HTML that wants to reference the local template variable inside the template:
<template [ngIf]="_model">
<input type="text" class="form-control" required [(ngModel)]="_model.firstName"
ngControl="test1" #myInput >
<br>Class (this works): {{myInput?.className}}
</template>
如果您需要显示与输入相关的模板块之外的内容,请使用 @ViewChildren('myInput') list:QueryList
然后订阅更改:
If you need to show something outside the template block related to the input, use @ViewChildren('myInput') list:QueryList<ElementRef>
and then subscribe to changes:
ngAfterViewInit() {
this.list.changes.subscribe( newList =>
console.log('new list size:', newList.length)
)
}
在 API 文档中查看更多 QueryList 方法.
See more QueryList methods in the API doc.
这篇关于*ngIf 和本地模板变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!