问题描述
在下面的示例中,我为多个单选按钮指定了局部变量#input
.单击<tr>
时,我想选择其中的单选按钮.
In the following example, I designate a local variable #input
to multiple radio buttons. When clicking the <tr>
I want to select the radio button inside.
以下代码可以正常工作,但是我不明白为什么.
And the following code works fine, but I don't understand why.
当Angular2的所有输入均具有局部变量#input
时,Angular2如何知道"我要引用的输入?
How can Angular2 "know" which input I'm refering to when ALL of them have the local variable#input
?
HTML
<tr *ngFor="let office of employee.offices" (click)="selectOffice(input)">
<td class="select-office-radio">
<input type="radio" name="office" #input />
</td>
<td>
{{office.officeName}}
</td>
</tr>
JS
selectOffice(input) {
input.checked = true;
}
推荐答案
正如Bhushan所说,ngFor
是结构指令,因此它是基于模板的结构的快捷方式.简而言之,可以在模板中将其分解为以下内容:
As Bhushan said, ngFor
is a structural directive so it's a shortcut for a template-based structure. In short, it can be desugared into the following in your template:
<template ngFor let-office [ngForOf]="employee.offices">
<tr (click)="selectOffice(input)">
(...)
</tr>
</template>
为模板定义局部变量的方法如下:
The way to define local variable for templates is the following:
- 添加前缀
let-
.例如,let-office
将定义一个变量office
. - 如果未定义值,则将使用模板上下文中的
$implicit
条目的值.就ngFor而言,它是迭代中的当前元素.此处:let-office
. - 您还可以指定一个值.例如,如果要为循环中的索引定义变量:
let-i="index"
.在这种情况下,变量i
将包含相应的值.
- Add the prefix
let-
. For example,let-office
will define a variableoffice
. - If you don't define a value, the value of the
$implicit
entry in the template context will be used. In the case of ngFor, it's the current element in the iteration. Here:let-office
. - You can also specify a value. For example, if you want to define a variable for the index in the loop:
let-i="index"
. In the case, the variablei
will contain the corresponding value.
关于用#
前缀定义的变量.如果它们所应用的元素不是组件,则它们对应于DOM元素.如果是组件,则对应于该组件.例如,<input #input/>
中的input
对应于ElementRef
,并且可以通过其nativeElement
属性访问DOM元素.
Regarding variables define with the #
prefix. They correspond to a DOM element if the element they apply on isn't a component. If it's a component, it corresponds to the component. For example, input
in <input #input/>
corresponds to an ElementRef
and the DOM element can be accessed through its nativeElement
property.
您还可以为此类变量指定一个值.在这种情况下,您可以选择应用于元素的特定指令.例如<input #ctrl="ngModel" [(ngModel)]="val"/>
.该值对应于指令声明中exportAs
属性中指定的值:
You can also specify a value for such variables. In this case, you can select a specific directive applied on the element. For example <input #ctrl="ngModel" [(ngModel)]="val"/>
. The value corresponds to what is specified within the exportAs
attribute in the directive declaration:
@Directive({
selector: 'child-dir',
exportAs: 'child'
})
class ChildDir {
}
@Component({
selector: 'main',
template: `<child-dir #c="child"></child-dir>`,
directives: [ChildDir]
})
class MainComponent {
}
这篇关于Angular2本地模板变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!