Angular 2个表单动态id和属性

Angular 2 forms dynamic id and for attributes

我在使用 forid 属性的 angular 中的 labelinput 元素之间创建 link 时遇到问题。给定以下代码:

@Component({
  selector: 'hello',
  template: `
<label [attr.for]="identifier">{{label}}</label>
<input [(ngModel)]="model" [attr.id]="identifier">
  `,
})
export class HelloComponent  {
  @Input() identifier: string;
}

我想要的是能够通过单击标签来聚焦输入字段,这是 web 中的默认行为。如果我静态设置属性,则此行为有效。或者,如果我从开发人员工具手动更新 DOM 中的属性。

我为 idfor 所做的尝试:

id="{{identifier}}"
[id]="identifier"
[attr.id]="identifier"

更新

找到问题了。检查下面的答案。

确实有效。查看 demo。您的组件 class.

中可能缺少正确的 属性 值

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  id = 'hello';
  label = 'hello';
  model = 'one';
}

app.component.html

<label [attr.for]="id">{{label}}</label>
<input [(ngModel)]="model" [attr.id]="id">

似乎问题出在如何在使用组件的地方绑定输入。因此,鉴于问题中的组件,以下内容不起作用:

<hello id="hello"></hello>

但是输入必须用方括号括起来:

<hello [id]="'hello'"></hello>

看来是因为和原生id属性冲突了。如果我将输入重命名为其他名称,第一种样式也有效。

<hello identifier="hello"></hello>

@Input() identfier: string;