0
<tab mousePosCollector></tab>

MousePosCollectorDirective都有TabComponent一个属性x。属性更改时如何x更新属性?TabComponentxMousePosCollectorDirective

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

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

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

谢谢!

4

1 回答 1

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)
  }
}
于 2016-10-05T20:03:15.090 回答