【问题标题】:How do I get the id of a form input element for a label in a reusable Angular component template?如何获取可重用 Angular 组件模板中标签的表单输入元素的 ID?
【发布时间】:2017-11-19 14:44:16
【问题描述】:

我有一个 Angular 2 组件,它包含一些表单输入元素和应该与之关联的标签。组件的多个实例可能同时在页面中。如何设置labelfor 属性和inputid 属性将它们相互连接?

如果我在模板中硬编码输入元素的 id,那么它在页面上就不会是唯一的。但我不想将标识符从其包含组件传递到该组件;标签和表单元素之间的连接只是这个组件的关注点。

<div>
    <label for="???">Name</label>
    <input [(ngModel)]="name" type="text" id="???"/>
</div>

AngularJS 有一个作用域 $id 属性,可以用来构建一个唯一的 id。 Angular 有没有类似的组件?

【问题讨论】:

    标签: angular


    【解决方案1】:

    一种方法是使用 @Input 装饰器并将值从您拥有组件的父组件传递到您的表单或标签所在的子组件

    父组件

    <myComponent idToUse="id1"></myComponent>
    <myComponent idToUse="id2"></myComponent>
    

    子组件

    @Component({
    selector : "myComponent",
    template: `<div>
        <label for="{{idToUse}}">Name</label>
        <input [(ngModel)]="name" type="text" id="{{idToUse}}"/>
    </div>`
    })
    export class childComponent {
    @Input() idToUse;
    }
    

    您可以在此链接Angular2 .. Using the same component to show different data on the same page depending on service response中找到多次使用相同组件的类似示例

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-26
      • 1970-01-01
      • 1970-01-01
      • 2015-01-30
      • 2019-08-20
      相关资源
      最近更新 更多