【问题标题】:Two way data binding between a component and a directive on the same element?组件和同一元素上的指令之间的两种方式数据绑定?
【发布时间】:2017-02-14 09:34:27
【问题描述】:
<tab mousePosCollector></tab>
MousePosCollectorDirective 和 TabComponent 都有一个属性 x。当x 中的属性x 发生变化时,如何在TabComponent 中更新属性x?
标准双向数据绑定似乎不是我的解决方案。
<tab mousePosCollector [(x)]="x"></tab>
这将在MousePosCollectorDirective 和TabComponent 的父组件之间启动双向数据绑定,而不是TabComponent 本身,这正是我想要的。
谢谢!
【问题讨论】:
标签:
angular
angular2-template
angular2-directives
angular-components
【解决方案1】:
我猜双向绑定应该可以工作Plunkr:
指令
@Directive({
selector: '[mousePosCollector]'
})
export class MousePosCollectorDirective {
@Input() x;
@Output() xChange = new EventEmitter();
ngOnInit() {
setTimeout(() => {
this.x = ++this.x;
this.xChange.emit(this.x);
}, 1000)
}
ngOnChanges() {
console.info(`Changes from MousePosCollectorDirective: ${this.x}`);
}
}
组件
@Component({
selector: 'tab',
template: `<h3>tab {{x}}</h3>`
})
export class TabComponent {
@Input() x;
@Output() xChange = new EventEmitter();
ngOnInit() {
setTimeout(() => {
this.x = ++this.x;
this.xChange.emit(this.x);
}, 2000)
}
ngOnChanges() {
console.info(`Changes from TabComponent: ${this.x}`);
}
}
父组件
@Component({
selector: 'my-app',
template: `
<tab mousePosCollector [(x)]="x"></tab>
{{x}}`
})
export class AppComponent {
x = 1;
ngOnInit() {
setTimeout(() => {
this.x = ++this.x;
}, 3000)
}
}