我理解如何使用ElementRef并且应该避免设置元素id,但是仍然存在想要设置元素id属性的情况。
例如,输入和标签(由于第三方CSS不能嵌套):
<input [attr.id]="'myinput'+instanceId" />
<label = [attr.for]="'myinput'+instanceId">My Label</label>
为了简单起见,我只是像这样递增一个数字:
let numInstances = 0;
@Component({
})
export class MyComponent {
private instanceId: number;
constructor(){
this.instanceId = numInstances++;
}
}
但我想知道是否有一个组件实例命名空间,我可以在模板中使用。像这样的?Angular2会将#替换为组件实例的唯一字符串。
<input [attr.id]="#myinput" />
<label = [attr.for]="#myinput">My Label</label>
如果这个不存在,你认为我应该向Angular2团队提出一个特性请求吗?
在阅读了网上的一些讨论后,我决定使用https://github.com/angular/angular/issues/5145#issuecomment-256354115中提出的lodash方法
它适用于我,希望它能帮助别人!