Pavel
Pavel

Reputation: 2101

How to set listener for data derived from child component? (Angular 5)

I have an example of two-way binding of the components. And I successfully got value in parent component, but I need to have the listener for this data, and due to data become from child component I don't understand how to set listener like (change).

@Component({
  selector: 'app-child',
  template: `
    <p>{{childData}}<br>
      <input [(ngModel)]="childData" type="text" (ngModelChange)="onChildDataChange($event)"></p>`
})
export class ChildComponent {
  @Input() childData: string;

  @Output() childDataChange: EventEmitter<string> = new EventEmitter<string>();

  onChildDataChange(data: string) {
    this.childDataChange.emit(this.childData);
  }
}

@Component({
  selector: 'app-parent',
  template: `<app-child [(childData)]="parentData"></app-child>`
})
export class ParentComponent {

  parentData: string = 'start value'

  log() {
    console.log(this.parentData);
  }
}

I try to add (change) event in ParentComponent like <app-child (change)="log()" [(childData)]="parentData"></app-child> but it dosen't work. I think it's due to app-child is another component but not HTML Tag.

How to binding my log() method to change of parentData variable?

Upvotes: 0

Views: 128

Answers (1)

ANewGuyInTown
ANewGuyInTown

Reputation: 6467

Well, why don't you try using the binding separately. There is no such thing as two way data binding in angular unlike angularJS.

The binding is uni-directional. That means data comes in through one way property binding and goes out thru user defined events.

So, what you can do in you parent component is:

<app-child [childData]="parentData" (childDataChange)="log()"></app-child>

Upvotes: 1

Related Questions