【问题标题】:Two way data binding between a component and a directive on the same element?组件和同一元素上的指令之间的两种方式数据绑定?
【发布时间】:2017-02-14 09:34:27
【问题描述】:
<tab mousePosCollector></tab>

MousePosCollectorDirectiveTabComponent 都有一个属性 x。当x 中的属性x 发生变化时,如何在TabComponent 中更新属性x

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

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

这将在MousePosCollectorDirectiveTabComponent 的父组件之间启动双向数据绑定,而不是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)
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-02-24
      • 2011-07-18
      • 2021-10-16
      • 2012-10-28
      • 2017-08-06
      • 2019-01-22
      • 2015-08-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多