NG模板出口在两个不同的循环内



>我需要在两个不同的地方重复相同的代码。 和配置文件 2 是数组。我想重复相同的HTML代码而不重复它们

   profile1 = [{name : 'mr.A1',age : 25  },
                {name : 'mr.B1',age : 23}];
   profile2 = [{name : 'mr.A2',age : 25  },
                {name : 'mr.B2',age : 23}];

      <ng-container *ngFor="let x of profile1">
      <ng-template #templateRef>
       <p> {{x.name}}</p>
      <p> {{x.age}}</p>
      </ng-template>
      <ng-template [ngTemplateOutlet]="templateRef"></ng-template>
      </ng-container>
     // above code shows the result
      mr.A1
      25
      mr.B1
      23
      // below code shows nothing
    <ng-container *ngFor="let x of profile2">
     <ng-template [ngTemplateOutlet]="templateRef"></ng-template>
    </ng-container>
    // i want following results using ngTemplateOutlet
      mr.A2
      25
      mr.B2
      23

这种动态行为最适合自定义组件。

但是,如果您想采用这种方式,请知道您必须使用 ngTemplateOutletContext 将数据发送到模板引用。

这是这样完成的:

<ng-template #profile let-person>
  <div>
    {{ person?.name }} is {{ person?.age }} years old.
  </div>
</ng-template>
<h1>First batch</h1>
<ng-container *ngFor="let person of profiles">
  <ng-container *ngTemplateOutlet="profile; context: { $implicit: person }"></ng-container>
</ng-container>
<h1>Second batch</h1>
<ng-container *ngFor="let person of profiles">
  <ng-container *ngTemplateOutlet="profile; context: { $implicit: person }"></ng-container>
</ng-container>

堆栈闪电战 - 文档

最新更新