【问题标题】:*ngFor on elements of ng-content Angular*ngFor 对 ng-content Angular 的元素
【发布时间】:2018-02-27 08:37:06
【问题描述】:

我想知道是否可以创建 .我需要对 ng-content 的每个元素使用不同的 css 类,因此我需要对 ng-content 的每个元素进行循环。有可能吗?

现在我将一个参数传递给子元素以枚举他,但我想在没有数字的情况下这样做。这是我的代码:

<sys-tab [tabs]="['Principal', 'Complementar']">
  <sys-tab-content [num]="1">
    <sys-panel header="Dados Gerais">
      <sys-input-text header="Nome" tam="1"></sys-input-text>

      <sys-input-mask header="CNPJ"></sys-input-mask>
      <sys-input-mask header="CNES"></sys-input-mask>
      <sys-input-mask header="Telefone"></sys-input-mask>

      <sys-input-text header="Email"></sys-input-text>
    </sys-panel>
  </sys-tab-content>
  <sys-tab-content [num]="2">
    <sys-input-text header="Email"></sys-input-text>
  </sys-tab-content>
</sys-tab>

如您所见,我将数字传递给孩子,以便我可以识别他是谁,但我想为 ng-内容创建一个循环,以便我可以为每个“sys-tab-content”添加不同的类"

【问题讨论】:

  • 您是否将 *ngFor 循环作为ng-content 传递给父组件。还是你手动添加里面的组件,就像上面的例子一样?
  • @Mihailo 我正在手动添加组件
  • 你为什么不手动添加类呢?
  • 这个想法是避免这样做,我可以保持现在的状态,传递数字,但这个想法是识别 ngcontent

标签: javascript angular typescript components angular2-ngcontent


【解决方案1】:

使用动态 ngTemplate 的简单列表示例

app.component.ts

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html'
})
export class AppComponent  {
  items = [ { name: 'abc' }, { name: 'cdf' }, { name: 'fgh' } ];
}

app.component.html

<nu-list [itemTpl]="itemTpl" [items]="items"></nu-list>
<ng-template let-item #itemTpl> 
    <h1>{{item.name}}</h1>
</ng-template>

list.component.ts

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

@Component({
  selector: 'nu-list',
  templateUrl: './list.component.html'
})
export class ListComponent  {

  @Input() itemTpl;
  @Input() items;

}

list.component.html

<ng-container *ngFor="let item of items">
  <ng-container *ngTemplateOutlet="itemTpl; context: {$implicit: item}"></ng-container>
</ng-container>

示例链接:https://stackblitz.com/edit/angular-list-ngtemplateoutlet

【讨论】:

    【解决方案2】:

    有两种方法可以添加“ngFor”或遍历子元素。

    一种是通过transclusion:另一种是通过检查父组件的ViewChildren。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-05
      • 2018-03-28
      • 1970-01-01
      • 2021-08-13
      • 1970-01-01
      • 2017-08-04
      • 2021-09-10
      相关资源
      最近更新 更多