Maxime Dupré
Maxime Dupré

Reputation: 5747

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

<tab mousePosCollector></tab>

The MousePosCollectorDirective and TabComponent both have a property x. How can property x be updated in the TabComponent when property x changes in the MousePosCollectorDirective?

Standard two way data binding does not seem to be a solution for my case.

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

This would initiate a two way data binding between the MousePosCollectorDirective and the parent component of TabComponent, not TabComponent itself, which is what I want.

Thanks!

Upvotes: 0

Views: 798

Answers (1)

yurzui
yurzui

Reputation: 214275

I guess two-way binding should work Plunkr:

directive

@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

@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}`);
  }
}   

parent component

@Component({
  selector: 'my-app',
  template: `
    <tab mousePosCollector [(x)]="x"></tab>
    {{x}}`
})
export class AppComponent {
  x = 1;
  ngOnInit() {
    setTimeout(() => {
      this.x = ++this.x;
    }, 3000)
  }
}

Upvotes: 1

Related Questions