Angular 2:单击相应组件中的关闭按钮时删除子组件

时间:2017-08-25 17:55:47

标签: angular

  

这是我的parent.html

parent.html 
<h1>Test for dynamic component</h1>
<button (click)="addBox('BoxOneComponent')">AddBoxOne</button>
<button (click)="addBox('BoxTwoComponent')">AddBoxTwo</button>
<div>
  <ng-template #parent></ng-template>
</div>
  

这是它的组成部分。

export class AppComponent implements AfterContentInit,OnInit {
  @ViewChild('parent',{read:ViewContainerRef}) parent;

  public resolve;

  constructor(private cfr:ComponentFactoryResolver){}

  addBox(val){
    let data;
    switch(val){
      case "BoxOneComponent":
        data = BoxOneComponent;
        break;
      case "BoxTwoComponent":
        data = BoxTwoComponent;
        break;
    }
    this.resolve = this.cfr.resolveComponentFactory(data);
    this.parent.createComponent(this.resolve);
  }

  ngOnInit(){

  }


  ngAfterContentInit(){

  }

}
  

这是我的孩子组件

import { Component, Input } from '@angular/core';

@Component({
  selector: 'box-one',
  template: `
    <div>
      <button (click)="delete()">Close</button>
    </div>
  `,
  styles: [`
    div{
      height:100px;
      width:100px;
      background-color:yellow;
      display:inline-block;
    }
    button{
      margin-left:50px;
    }
  `]
})
export class BoxOneComponent  {


}

我可以动态添加组件。现在我想在单击相应子组件中存在的按钮时动态删除子组件。我知道我们必须使用ViewContainerRef.remove(子索引)。但是如何获取子组件的索引引用父类?

演示:Working Demo

1 个答案:

答案 0 :(得分:0)

您的动态组件需要以某种方式通知父组件应该删除它。我能想到的最简单的方法是在父级可以订阅的组件实例中提供一个Obseravvble(一个Promise也可以工作)。

对于类型安全,您还可以为这些组件创建一个接口(指定它们必须在内部具有close$可观察的内容。)

<button (click)="close()">Close</button>

public close$ = new Subject<void>()
public close() {
  this.close$.next(null)
}

const cmp: ComponentRef<any> = this.parent.createComponent(this.resolve);
cmp.instance.close$.take(1).subscribe(() => cmp.destroy())

这是working demo