【问题标题】:Angular 2 Child Component removing Item from Parent Component ArrayAngular 2子组件从父组件数组中删除项目
【发布时间】:2016-06-16 00:25:38
【问题描述】:

当前子组件尝试删除父组件的数组时遇到问题。

父组件:

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

export class ParentComponent {

    public items = [];
}

父 HTML

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

子组件

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

export class ChildComponent{
    @Input() items;

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

但是,当我调用 emptyItems/addItem 函数时,子视图中的 items 数组将反映更改,但在父组件上它不会更改。

我需要使用输出吗?

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

    正确的方法是使用Outputhttps://angular.io/docs/ts/latest/cookbook/component-communication.html#

    但是我们可以在您的items 上使用双向绑定,这将反映双方的变化:

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

    查看更多详情https://angular.io/docs/ts/latest/guide/cheatsheet.html

    更新: 尝试以不同的方式清空数组How do I empty an array in JavaScript?

    Output 应该可以工作https://angular.io/docs/ts/latest/api/core/index/Output-var.html 这个想法是你必须将更新的东西从 child 传递给 parent 并手动更新 parent

    的成员 items

    【讨论】:

    • 这对我不起作用,我调用了 emptyItems 函数并希望它不会显示任何项目,但它没有对父对象做任何事情
    猜你喜欢
    • 2018-09-15
    • 1970-01-01
    • 2018-03-03
    • 2017-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-17
    相关资源
    最近更新 更多