我的组件中有一个复选框,其绑定如下:
<input type="checkbox" [name]="name" [id]="id" /><label [htmlFor]="id"></label>
当组件加载时,我可以检查元素并发现传递给这些输入的值是绑定的,但是当我单击标签时,复选框不会被检查。
我也是这样试过的:
<input type="checkbox" [attr.name]="name" [attr.id]="id" /><label [attr.for]="id"></label>
<input type="checkbox" name="{{name}}" id="{{id}} /><label [attr.for]="id"></label>
及其组合。它们都产生相同的效果,绑定数据,不选中复选框。
这是我的组件:
import { Component } from '@angular/core';
@Component({
inputs: ['name', 'id'],
selector: 'my-checkbox',
templateUrl: 'app/form/input/checkbox.component.html'
})
export class CheckboxComponent {}
使用的HTML:
<my-checkbox name="test-name" id="test-id"></my-checkbox>
答案 0 :(得分:1)
尝试以下方法之一:
std::vector
您需要将值作为字符串<my-checkbox [name]="'test-name'" [id]="'test-id'"></my-checkbox>
<my-checkbox name="test-name" [id]="'test-id'"></my-checkbox>
传递,并且要将表达式计算为字符串,必须将其放在引号[property]="experession"
中。
答案 1 :(得分:1)
When you are using id
as input name, you get your component as dom-element with this id. It adds same id to the checkbox, and for
of the label. But when you have multiple elements with same id, label refers to first of them. In your case it refers you component instead of input
.
Just rename input parameter.
By the way, it would've be right to declare corresponding field in ts class.
http://plnkr.co/edit/JazXV3Oi91hSBTdVlBHh?p=preview
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<my-checkbox-broken id="test-id-1"></my-checkbox-broken><br>
<my-checkbox-broken [id]="'test-id-2'"></my-checkbox-broken> can work too<br>
<my-checkbox-working chkId="test-id-3"></my-checkbox-working><br>
<output></output>
`
})
export class AppComponent {
}
@Component({
inputs: ['id'],
selector: 'my-checkbox-broken',
template: '<input type="checkbox" [id]="id" /><label [htmlFor]="id">Broken :(</label>'
})
export class CheckboxComponent_Broken {
id: string;
}
@Component({
inputs: ['chkId'],
selector: 'my-checkbox-working',
template: '<input type="checkbox" [id]="chkId" /><label [htmlFor]="chkId">Working!</label>'
})
export class CheckboxComponent_Working {
chkId: string;
}
document.addEventListener('click', ({ target: { htmlFor: id } }) => {
if (id) {
document.querySelector('output').textContent = id + " is " + document.getElementById(id).tagName;
}
})
答案 2 :(得分:0)
以下是否有效?
<input type="checkbox" name="{{name}}" id="{{id}} /><label for="{{id}}"></label>