2017-08-16 122 views
0

我正在使用angularjs 4.3.4通过角度CLI工作正常。但是我越来越奇怪的问题。我用复选框和标签创建了一个自定义组件。 id和属性值来自自定义标签属性。当我看到html代码时,我可以看到它已经按照预期生成了id和for属性。但点击标签不会检查或取消选中该复选框。这是我的代码:Angualr 4x标签不起作用

input.component.html(选项1)

<div class="form-group input-group"> 
    <span> 
     <input id="{{id}}" type="checkbox" placeholder="Name"/> 
     <label for="{{id}}">{{title}}</label> 
     </span> 
</div> 

input.component.html(选项2)

<div class="form-group input-group"> 
    <span> 
     <input bind.id="id" type="checkbox" placeholder="Name"/> 
     <label bind.for="id">{{title}}</label> 
     </span> 
</div> 

input.component.html(选项3)

<div class="form-group input-group"> 
    <span> 
     <input [id]="id" type="checkbox" placeholder="Name"/> 
     <label [for]="id">{{title}}</label> 
     </span> 
</div> 

input.component.html(方案4)的上述选项

<div class="form-group input-group"> 
    <span> 
     <input attr.id="id" type="checkbox" placeholder="Name"/> 
     <label attr.for="id">{{title}}</label> 
     </span> 
</div> 

无正在工作。

input.component.ts

import { Component, OnInit, Input } from '@angular/core'; 

@Component({ 
    selector: 'my-input', 
    templateUrl: './input.component.html', 
    styleUrls: ['./input.component.less'] 
}) 
export class InputComponent implements OnInit { 
    @Input() title: string; 
    @Input() id: string; 
    constructor() { } 

    ngOnInit() { 
    } 

} 

app.component.html

<my-input title="Testing" id="checkBox"></my-input> 

请帮帮我,我该怎么解决呢?

感谢

回答

2

尝试这种解决方案之一:

<label [attr.for]="id">{{title}}</label> 
<label attr.for="{{id}}">{{title}}</label> 
<label htmlFor="{{id}}">{{title}}</label> 

与plunker:https://plnkr.co/edit/RI0bmtX1kceDdd3xt1g6?p=preview

+0

我不能使它工作。在这里,我尝试了一次强盗,但它根本不工作。我不知道我做错了什么。 https://plnkr.co/edit/QZjkT47TnKIVRaZRvSNi?p=preview – Riy

+0

我解决了你的问题,看看https://plnkr.co/edit/ycvUFl39KCafepYgLjOz?p=preview – Vega

+0

谢谢维加解决我的问题:)。然而,这不是问题。我刚刚添加了我的答案 – Riy

0

@Vega您的帮助感谢。我想清楚我的复选框组件代码出了什么问题。

如果其他人正在寻找相同问题的解决方案,这里是工作示例。

https://plnkr.co/edit/UTXmMEW2jEE1lblnKMuK?p=preview. 

要求是使自定义CheckBox组件与标题和id属性

问题, 上面提到的代码工作正常,并呈现与标题复选框。当你点击复选框的标题时,应该选中该复选框,但它没有。

原因:自定义输入组件的ID属性,即使它是一个自定义组件,有它自己的定义id属性的HTML标签属性/属性。由于ID是一个HTML属性,因此角度会忽略它并且不会传输到自定义组件输入属性。

溶液1:改变输入属性ID在定制组件本身份识别码

<my-input title="Does Work" myid="checkbox2"></my-input> 

溶液2:通过定制组件的ID属性作为一个双向数据绑定

正确方法检查我考绩值

<my-input title="Does Work" [id]="'checkbox2'"></my-input> 

标识错误的方式

<my-input title="Does Work" [id]="checkbox2"></my-input> 
<my-input title="Does Work" id="checkbox2"></my-input> 

的方式,我希望这将帮助我这样的人。

Riy