Angular 4-component two-way binding problem

I have an array:

const a = [apple,ball,cat]

I pass this on to two components:

<app-header [appData]="data"  ></app-header>

<list-todo [appData]="data" [getData]="getData" [setData]="setData" ></list-todo>

In component appHeader

export class appHeader  {
  @Input('appData') data : any

  clear(){
    this.data = []
  }
}

the execution of the function clear()does not affect the array in the component listTodo. Is there any way to solve this problem?

I also checked two-way attribute binding, but nothing else worked!

+6
source share
2 answers

By doing this this.data = [], you are not freeing your array, but replacing it with a new instance. Your parent component and another child component are still referencing the source instance, which leads to a description of your behavior.

One solution is to remove the original array instead of replacing it:

clear() {
    this.data.length = 0;
}

, .

+5

Input , , , . this.appData ( ). appData . , , . ;)

, changed component Output [(appData)]="data" ( EventEmitter ).

AppComponent

 <app-header [appData]="data"  ></app-header>
<list-todo [(appData)]="data"></list-todo>

ListTodoComponent

@Component({
  selector: 'list-todo',
  template: `
     <ul>
      <li *ngFor="let item of appData">{{item}}</li>
     </ul>
     <button (click)="clear()">Clear</button>
  `
})
export class ListTodoComponent { 
  @Input() appData;
  @Output() appDataChange: EventEmitter<any> = new EventEmitter<any>();

  clear(){
    this.appData = [];
    //this emit is important to send data back to parent.
    //make sure you should have `Change` prefix to bounded value, like `appData` + `Change` = `appDataChange`, 
    //which ultimately saves few lines of code.
    this.appDataChange.emit(this.appData); 
  }
}

+6

All Articles