问题
I am working with Angular2 RC5. I have a component encapsulating a label and an input
import { Component, Input} from '@angular/core';
@Component({
selector: 'my-input',
template: `
<div class="mx-field" >
<label [attr.for]="id"><ng-content></ng-content></label>
<input
type='text'
id = "{{id}}"
/>
</div>
`
})
export class InputComponent {
@Input() id: string;
}
It is called from any template as follows <my-input id="inputcontrol">input</my-input>
The problem is that when I click on the label the input does not get focused, although when I check the dev tools in the browser both the for and id attributes are correctly set
here is a plunker showing the issue: https://plnkr.co/edit/WGhg597MzJ5df4f0Hm5n
回答1:
Well I found a hack for now, If I send it using a name other than id it works. ie:
import { Component, Input} from '@angular/core';
@Component({
selector: 'my-input',
template: `
<div class="mx-field" >
<label [attr.for]="ident"><ng-content></ng-content></label>
<input
type='text'
id = "{{ident}}"
/>
</div>
`
})
export class InputComponent {
@Input() ident: string;
}
and then from the templates call it <my-input id="inputcontrol">input</my-input>
this works.
The problem was that the DOM had multiple elements (angular component and the input) with the same id
来源:https://stackoverflow.com/questions/39163205/angular2-the-for-attribute-on-a-label-does-not-link-it-to-the-input