Angular2 the for attribute on a label does not link it to the input

情到浓时终转凉″ 提交于 2019-12-24 08:00:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!