【发布时间】:2018-09-08 00:11:06
【问题描述】:
这是在 Angular 中创建双向数据绑定的方法:https://blog.thoughtram.io/angular/2016/10/13/two-way-data-binding-in-angular-2.html#creating-custom-two-way-data-bindings
例如我在一个组件中创建了counter 双向数据绑定属性。有用。现在我还想收到有关使用组件的counterChange 输出更改属性的通知。
这里是组件的代码:
export class CustomCounterComponent {
counterValue = 0;
@Output() counterChange = new EventEmitter();
@Input()
get counter() {
return this.counterValue;
}
set counter(val) {
this.counterValue = val;
this.counterChange.emit(this.counterValue);
}
decrement() {
this.counter--;
}
increment() {
this.counter++;
}
}
这是我的使用方法:
@Component({
selector: 'my-app',
template: `
<custom-counter [(counter)]="counterValue" (counterChange)="onChange($event)"></custom-counter>
<p><code>counterValue = {{counterValue}}</code></p>
`
})
export class AppComponent {
onChange(value) {
console.log('onChange!', value)
}
counterValue = 5;
}
期望的行为:我希望 onChange 在值更改时被调用 1 次。
具体问题:onChange 每次值变化时都会被调用两次。
任何想法为什么它被称为 2 次?
另外,我有完整的 plunkr 示例:https://plnkr.co/edit/8HGXNhhYQRoLVJeDlqWK?p=preview。只需打开控制台并查看那里。
【问题讨论】:
标签: angular