同一元素上的组件和指令之间的两种方式数据绑定?

Two way data binding between a component and a directive on the same element?

<tab mousePosCollector></tab>

MousePosCollectorDirectiveTabComponent 都有一个 属性 x。当 属性 xMousePosCollectorDirective 中更改时,属性 x 如何在 TabComponent 中更新?

标准双向数据绑定似乎不是我的解决方案。

<tab mousePosCollector [(x)]="x"></tab>

这将在 MousePosCollectorDirectiveTabComponent 的父组件之间启动双向数据绑定,而不是 TabComponent 本身,这正是我想要的。

谢谢!

我想双向绑定应该可行 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)
  }
}