2
我正試圖做一個簡單的角度2組件顯示一個開關按鈕。 它幾乎工作,但使用ngModel時父值不更新。Angular 2:無法獲得兩種方式在自定義組件中的綁定
這裏是我的自定義組件:
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;
}
}
對此有何建議?
所以,如果我理解正確的輸出變量實際上是輸入變量名+「變」串聯? – Julien
是的。這是針對相同屬性名稱設置的特定命名約定。 https://angular.io/docs/ts/latest/guide/template-syntax.html#!#two-way –