使用代码从模板 ngFor 中生成的 DOM 中删除组件

remove component from DOM generated in template ngFor using code

我有一个独特的场景,我需要创建 child 组件,这些组件在创建时需要从我的后端获取一些信息。我的流程如下:

1) parent 组件的模板文件有一个 *ngFor 创建 n 个 child 组件

2) 在 child 组件的创建指令中,我包括两个事件发射器来监听 parent(一个用于创建以添加到数组,一个用于删除)

3) 当 child 组件启动时,我从后端收集该组件所需的内容,然后使用 ngOnInit() 中的创建事件发射器通知 parent 准备好了。

4) parent 然后将 child 组件添加到其 children

数组中

5) 在 child 组件中,有一个 link 用于删除那个 child,它也会发出该事件直到 parent,parent 从数组中删除该实例。

以上所有都正常工作,但我还需要在 child 传递删除事件时从 parent 的模板中删除实际的 HTML。我在这里查看:,这是我需要的,但它假设 child 组件是在代码中生成的,而不是在模板中生成的。

我假设我需要使用类似的东西并将我的 child 组件引用添加到我的 @ViewChild 容器,但我没有在 container 上看到任何允许的方法我去 AddFromTemplate() 等等

这是一些代码:

Parent 组件 (ts):

export class MatParentComponent implements OnInit {
  constructor(private someService: SomeService) { }
  @ViewChild('container', { read: ViewContainerRef, static: false }) container: ViewContainerRef;
  // dunno how to use container in this example to add references to child components for removal from HTML later
  matChildComponents: MatChildComponent[] = [];

  addInstanceToCollection(matChildComponent: MatChildComponent): void {
    this.matChildComponents.push(matChildComponent);
  }
  removeInstanceFromCollection(matChildComponent: MatChildComponent): void {
    let i: number = 0;
    for (let i = 0; i < this.matChildComponents.length; i++) {
      if (this.matChildComponents[i] == matChildComponent) {
        console.log(i);
        this.matChildComponents.splice(i, 1);
        break;
      }
    }
  }


  ngOnInit() {
  }
}

及其对应的模板HTML:

<mat-child *ngFor="let instance of instances"
            [someProp1]="instance.someProp1"
            [someProp2]="instance.someProp2"
            (instanceCreatedEmitter)="addInstanceToCollection($event)"
            (instanceRemoveEmitter)="removeInstanceFromCollection($event)"></mat-child>

child 组件 (ts):

export class MatChildComponent implements OnInit {
  @Input() someProp1: string;
  @Input() someProp2: string;
  @Output() instanceCreatedEmitter = new EventEmitter<MatChildComponent>();
  @Output() instanceRemoveEmitter = new EventEmitter<MatChildComponent>();

  constructor() { }

  removeThisComponent(): void {
    this.instanceRemoveEmitter.emit(this);
  }

  ngOnInit() {
    // do my stuff from back end to fully load up this component
    this.componentLoaded = true;
    // now emit this instance back to the parent so they can add it to their collection
    this.instanceCreatedEmitter.emit(this);
  }
}

我应该使用这种 @ViewChild() 方法吗?还有什么我可以做的吗?我可以在发出删除事件后从它自己的实现中删除 child 组件吗? IE:类似于 this.destroy().

TIA

想通了。在我上面画的图片中,我只需要从 instances 数组中删除我在父容器的 HTML 模板中循环的项目。