我正在尝试为复选框等输入创建一个包装器组件,但我无法更改父 (inputValue) 变量,即使它被设置为 ngModel。
这是我的组件定义:
@Component({
selector: 'my-checkbox',
inputs: ['inputValue', 'label'],
template: `
<div class="ui checkbox">
<input type="checkbox" name="example" [(ngModel)]="inputValue" (change)="onChange($event)">
<label>{{label}}</label>
</div>`
})
export class CheckboxComponent {
inputValue: boolean;
onChange(event) {
this.inputValue = event.currentTarget.checked;
console.log(this.inputValue);
}}
我在父 View 中这样使用它:
<my-checkbox [inputValue]="valueToUpdate" [label]="'Test Label'"></my-checkbox>
控制台确实正确记录,我可以看到内部 (inputValue) 正在更新,但外部“valueToUpdate”没有更新(ngModel 双向绑定(bind)未正确更新)。
最佳答案
您需要为您的组件定义一个输出并使用 EventEmitter
类来触发相应的事件。
@Component({
selector: 'my-checkbox',
inputs: ['inputValue', 'label'],
outputs: ['inputValueChange']
template: `
<div class="ui checkbox">
<input type="checkbox" name="example" [(ngModel)]="inputValue" (change)="onChange($event)">
<label>{{label}}</label>
</div>`
})
export class CheckboxComponent {
inputValue: boolean;
inputValueChange: EventEmitter<any> = new EventEmitter();
onChange(event) {
this.inputValue = event.currentTarget.checked;
console.log(this.inputValue);
this.inputValueChange.emit(this.inputValue);
}
}
这样你就可以为你的子组件使用两个绑定(bind):
<my-checkbox [(inputValue)]="valueToUpdate" [label]="'Test Label'">
</my-checkbox>
关于angularjs - 带有ngModel的Angular 2组件不更新父模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35580721/