【发布时间】:2017-03-29 12:06:18
【问题描述】:
我正在尝试制作一个显示开关按钮的简单 angular 2 组件。 它几乎可以工作,除了使用 ngModel 时没有更新父值。
这是我的自定义组件:
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-switch',
template:`
<label class="switch">
<input id="switch" type="checkbox" [(ngModel)]="checked">
<div class="slider round"></div>
</label> `,
styleUrls: ['./switch.component.css']
})
export class SwitchComponent {
checkValue:boolean;
@Output() checkChange = new EventEmitter();
@Input()
get checked() {
return this.checkValue;
}
set checked(val) {
this.checkValue = val;
this.checkChange.emit(this.checkValue);
console.log("from switch: value = " + this.checkValue);
}
}
这是我的自定义子组件的 2 个实例的父组件。 - 第一个实例工作正常,但使用分离的属性 [] 和事件 () 绑定 - 第二个是使用两种方式绑定 [()] 但不工作。知道我错过了什么吗?
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template:`
<app-switch [checked]="checkValue" (checkChange)="onCheckChanged($event)"></app-switch>
<div>checkBox :<span>{{checkValue}}</span></div>
<hr/>
<app-switch [(checked)]="switchValue" ></app-switch>
<div>checkBox :<span>{{switchValue}}</span></div>`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app works!';
checkValue:boolean = false;
switchValue:boolean = false;
onCheckChanged($event){
console.log("from AppComponent : " + $event);
this.checkValue = $event;
}
}
对此有何建议?
【问题讨论】: