Enl*_*dZA 3 angularjs angular2-directives angular
我正在尝试为输入创建一个包装器组件,例如复选框,但我无法更改父(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);
}}
Run Code Online (Sandbox Code Playgroud)
我在父视图中使用它:
<my-checkbox [inputValue]="valueToUpdate" [label]="'Test Label'"></my-checkbox>
Run Code Online (Sandbox Code Playgroud)
控制台确实正确记录,我可以看到内部(inputValue)正在更新但不是外部'valueToUpdate'(ngModel双向绑定未正确更新).
您需要为组件定义输出,并使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
这样您就可以为子组件使用两个绑定:
<my-checkbox [(inputValue)]="valueToUpdate" [label]="'Test Label'">
</my-checkbox>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5306 次 |
| 最近记录: |