在以下示例中,我#input为多个单选按钮指定了一个局部变量。单击时<tr>我想选择里面的单选按钮。
下面的代码工作正常,但我不明白为什么。
当所有输入都具有局部变量时,Angular2 如何“知道”我指的是哪个输入#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>
Run Code Online (Sandbox Code Playgroud)
JS
selectOffice(input) {
input.checked = true;
}
Run Code Online (Sandbox Code Playgroud)
正如 Bhushan 所说,ngFor是一个结构指令,所以它是基于模板的结构的快捷方式。简而言之,它可以在您的模板中脱糖为以下内容:
<template ngFor let-office [ngForOf]="employee.offices">
<tr (click)="selectOffice(input)">
(...)
</tr>
</template>
Run Code Online (Sandbox Code Playgroud)
为模板定义局部变量的方法如下:
let-。例如,let-office将定义一个变量office。$implicit则将使用模板上下文中条目的值。在 ngFor 的情况下,它是迭代中的当前元素。这里:let-office。let-i="index". 在这种情况下,变量i将包含相应的值。关于用#前缀定义的变量。如果它们应用的元素不是组件,则它们对应于 DOM 元素。如果是组件,则对应组件。例如,inputin<input #input/>对应于 anElementRef并且可以通过其nativeElement属性访问 DOM 元素。
您还可以为此类变量指定一个值。在这种情况下,您可以选择应用于元素的特定指令。例如<input #ctrl="ngModel" [(ngModel)]="val"/>。该值对应exportAs于指令声明中属性中指定的内容:
@Directive({
selector: 'child-dir',
exportAs: 'child'
})
class ChildDir {
}
@Component({
selector: 'main',
template: `<child-dir #c="child"></child-dir>`,
directives: [ChildDir]
})
class MainComponent {
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14666 次 |
| 最近记录: |