Angular Two-Way Data Binding and Watching for Chan

2019-06-13 15:48发布

It seems there is no way to watch changes in the parent component when using two-way data binding.

I have a custom input component for collecting a tag list. Two-way data binding is setup and working between this component and its parent.

// the parent component is just a form
// here is how I'm adding the child component
<input-tags formControlName="skillField" [(tags)]='skillTags' (ngModelChange)="skillTagUpdate($event)"></input-tags>

In the parent component how do you watch the bound variable for changes? While it's always up to date (I've confirmed this) I cannot find any guidance on reacting to changes.

I've tried:

ngOnChanges(changes: SimpleChanges) {
    if (changes['skillTags']) {
        console.log(this.skillTags);  // nothing
    }
}

and

skillTagUpdate(event){
    console.log(event); // nothing
}

1条回答
Viruses.
2楼-- · 2019-06-13 16:31

you could listen to the change:

<input-tags formControlName="skillField" [tags]='skillTags' (tagsChange)='skillTags=$event; skillTagUpdate();'></input-tags>

or use getter and setter:

get skillTags(): string {
    return ...
}
set skillTags(value) {
    variable = value;
}

another approach:

 export class Test implements DoCheck {
  differ: KeyValueDiffer<string, any>;
  public skillTags: string[] = [];
  ngDoCheck() {
    const change = this.differ.diff(this.skillTags);
    if (change) {
      change.forEachChangedItem(item => {
        doSomething();
      });
    }
  }
  constructor(private differs: KeyValueDiffers) {
    this.differ = this.differs.find({}).create();
  }
}}
查看更多
登录 后发表回答