首页 文章

告诉父组件从同一子组件中删除子组件

提问于
浏览
0

我有一个Angular父组件,它根据一个值创建一个包含几个子组件的数组(例如,1个ParentComponent创建10个ChildComponents) . ChildComponent具有显示多个按钮的HTML,包括删除按钮 . 删除按钮同时使子组件自行删除 .

删除ChildComponent后,我该如何通知父改变?删除后,父级仍然在其ChildComponents数组中包含已删除的对象 . 我看过有关使用Output EventEmitter的帖子,但是没有EventEmitter可以做到这一点吗?

1 回答

  • 1

    如果使用ngFor指令创建子组件循环,则应该能够直接从父级调用delete方法 . 例如:

    HTML

    <div *ngFor="let item of items; index as i;">
      <div>{{name}}</div>
      <button (click)="delete(i)"></button>
    </div>
    

    零件

    import { Component } from "@angular/core";
    
    @Component({
      selector: "app",
      templateUrl: "./app.html",
    })
    export class AppComponent {    
      public items = [{name: "first"}, {name: "second"}];
    
      public delete(index: number) {
        this.items.splice(index, 1);
      }
    }
    

    每个子组件都可以直接从父组件调用delete方法,然后使用索引指示应该删除列表中的哪个项目 .

相关问题