如何在ngFor循环中填充Angular嵌套组件?

时间:2019-09-22 18:49:07

标签: angular angular7

我在html端有一个嵌套组件,如下所示:

<main>
   <ng-content *ngFor="let item in data">
     <car *ngIf="item.type=='car'"></car>
     <plane *ngIf="item.type=='car'"></plane>
   </ng-content>
</main>

我的carplane组件被实现为基本的车载类。

export abstract class BaseVehicleComponent{
    onVehicleCreated(){
        console.log("on vehicle created.")
    }
}

创建车辆后,我想在main组件中填充一个事件。

@Component({
   selector: 'main',
})
export class MainComponent{

     @Output() vehicleCreated = new EventEmitter<void>();

}

HML像这样更新:

<main (vehicleCreated)="onVehicleCreated($event)">
   <ng-content *ngFor="let item in data">
     <car *ngIf="item.type=='car'"></car>
     <plane *ngIf="item.type=='car'"></plane>
   </ng-content>
</main>

但是基地火法不会开火。

1 个答案:

答案 0 :(得分:0)

BaseVehicleComponent应该有EventEmitter而不是MainComponent

BaseVehicleComponent:

export abstract class BaseVehicleComponent{
   @Output() vehicleCreated = new EventEmitter<void>();
}

MainComponent应该具有onVehicleCreated()功能而不是BaseVehicleComponent

MainComponent:

export class MainComponent{  
  onVehicleCreated(){
    console.log("on vehicle created.")
  }
}     

carplane组件的ngOnInit()方法中,调用事件发射器的emit()方法。

this.vehicleCreated.emit();

MainComponent的模板修改为

<ng-container *ngFor="let item in data">
  <car *ngIf="item.type=='car' (vehicleCreated)="onVehicleCreated($event)"></car>
  <plane *ngIf="item.type=='plane' (vehicleCreated)="onVehicleCreated($event)"></plane>
</ng-container>

StackBlitz上的实时演示:https://stackblitz.com/edit/angular-thvzue

有关更多信息,请查看我的answer关于父子组件之间的通信。