Angular 2 Child Component removing Item from Paren

2019-09-12 15:59发布

问题:

Currently having issue with Child component trying to remove Parent component's Array.

Parent Component:

@Component({
    selector: 'parent',
    templateUrl: 'app/templates/parent.html'
})

export class ParentComponent {

    public items = [];
}

Parent HTML

  <child [items]="items"></child>
  <product *ngFor="let item of items><product>

Child component

@Component({
    selector: 'child',
    templateUrl: 'app/templates/child.html'
})

export class ChildComponent{
    @Input() items;

    emptyItems() {
        this.items = [];
    }
    addItem() {
        this.items.push({'title': 'foo'});
    }
}

However when I call emptyItems/addItem function, the items array in the child view will reflect on changes, however on the parent component it doesnt change.

Do I need to use Output?

回答1:

The right way is to use Output https://angular.io/docs/ts/latest/cookbook/component-communication.html#

However we can use two-ways binding on your items, this will reflect changes on both sides:

<child [(items)]="items"></child>

See more details https://angular.io/docs/ts/latest/guide/cheatsheet.html

Update: Try to empty you array differently How do I empty an array in JavaScript?

Output should work https://angular.io/docs/ts/latest/api/core/index/Output-var.html The idea is that you have to pass updated things from child to parent and manually update member items of the parent