繁体   English   中英

如何使用 angular 在“ngFor”循环内创建模板引用?

[英]How to create template reference inside the `ngFor` loop with angular?

我正在尝试通过ngFor循环创建模板引用。 但不起作用。

ts文件:

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  members = [
    {
      name: 'name1',
      id:"one"
    },
    {
      name: 'name2',
      id:"two"
    },
    {
      name: 'name3',
      id:"three"
    } 
  ]
}

模板:

<div class="container">
  <h2>Test popover</h2>
  <p>
    How to declare a dynamic template reference variable inside a ngFor element?
  </p>
</div>

<div *ngFor="let member of members">
  <ng-container [ngTemplateOutlet]="{{member.id}}"
    >Hello, <b>{{ member.name }}</b
    >!</ng-container
  >
</div>

<ng-template #one> one </ng-template>
<ng-template #two> two </ng-template>
<ng-template #three> three </ng-template>

现场演示

我收到一个错误:

Type '{ "": any; }' is not assignable to type 'TemplateRef<any>'. Object literal may only specify known properties, and '""' does not exist in type 'TemplateRef<any>'.

更新:

如果你想将ngTemplate传递给孩子,你可以使用contentChild

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

@Component({
  selector: 'hello',
  template: `
  <div *ngFor="let member of members">
      {{member.name}} <ng-container [ngTemplateOutlet]="this[member.id]"></ng-container>
  </div>
  `,
  styles: [`h1 { font-family: Lato; }`],
})
export class HelloComponent {
  @ContentChild('one') one: TemplateRef<any>;
  @ContentChild('two') two: TemplateRef<any>;
  @ContentChild('three') three: TemplateRef<any>;
  @Input() members: any;
}

分叉的堆栈闪电战

解决方案1:

您可以根据索引进行渲染,而不是对模板名称进行硬编码

<div class="container">
  <h2>Test popover</h2>
  <p>
    How to declare a dynamic template reference variable inside a ngFor element?
  </p>
</div>
<div *ngFor="let member of members; let i = index">
  <ng-container *ngIf="temps">
    <ng-container [ngTemplateOutlet]="temps.toArray()[i]"
      >Hello, <b>{{ member.name }}</b
      >!</ng-container
    ></ng-container
  >
</div>

<ng-template #temp> one </ng-template>
<ng-template #temp> two </ng-template>
<ng-template #temp> three </ng-template>

分叉的堆栈闪电战

解决方案2:

您可以链接三元条件,以便根据需要获得 output

<div class="container">
  <h2>Test popover</h2>
  <p>
    How to declare a dynamic template reference variable inside a ngFor element?
  </p>
</div>

<div *ngFor="let member of members">
  <ng-container
    *ngTemplateOutlet="
      member.id === 'one' ? one : member.id === 'two' ? two : three
    "
    >Hello, <b>{{ member.name }}</b
    >!</ng-container
  >
</div>

<ng-template #one> one </ng-template>
<ng-template #two> two </ng-template>
<ng-template #three> three </ng-template>

分叉的堆栈闪电战

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM