具有多种内容类型的 ContentChildren

2023-11-25

您好,我目前正在构建一个允许其中包含多种列类型的表。我希望能够像这样使用它:

<my-table [rows]="rows">
     <text-column [someParameters]="here" header="text"></text-column>
     <icon-column [someParameters]="here" header="icon"></icon-column>
</my-table>

text-column and icon-column是单独的指令。

我目前有一个名为的抽象类column让我们说text-columnicon-column可能看起来像:

   export abstract class Column
   {
       @Input() someParameters:string;
       @Input() header:string;
   }

   export class TextColumnDirective extends Column
   {
      //I do cool stuff here
   }

   export class IconColumnDirective extends Column
   {
      //I do different cool stuff   
   }

我的桌子可能看起来像:

@Component({
   selector:'my-table',
   template: `
        <table>
            <thead>
                <tr>
                   <th *ngFor="let column of columns">{{column.header}}</th>
                </tr>
            </thead>
        </table>
   `
})
export class MyTableComponent
{
    @ContentChildren(Column) columns:QueryList<any>;

    //I do cool stuff too
}

因此,如果我不使用摘要而仅使用文本列来调用它,则这种方法有效@ContentChildren(TextColumnDirective) columns:QueryList<any>;但只获取文本列,与图标列相同。我怎样才能做到这一点,稍后我可以为不同的列类型添加不同类型的指令?


@3xGuy 的答案是正确的,但是forwardRef(() => {})除非提供的类型是在装饰器或被装饰类之后定义的,否则不需要请参阅这篇 Angular 深入文章

请注意,此方法可用于ContentChildren or ViewChildren,下面我用ViewChildren

item.ts

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

export class Item {
  color = '';
}

@Directive({
  selector: '[blueItem]',
  providers: [{ provide: Item, useExisting: BlueItemDirective }],
})
export class BlueItemDirective { // 'extends Item' is optional
  color = 'blue';
}

@Directive({
  selector: '[redItem]',
  providers: [{ provide: Item, useExisting: RedItemDirective }],
})
export class RedItemDirective { // 'extends Item' is optional
  color = 'red';
}

应用程序组件.ts

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

import { Item } from './item';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Multiple View Child Types';

  // Note we query for 'Item' here and not `RedItemDirective'
  // or 'BlueItemDirective' but this query selects both types
  @ViewChildren(Item) viewItems: QueryList<Item>;

  itemColors: string[] = [];

  ngAfterViewInit() {
    this.itemColors = this.viewItems.map(item => item.color);
  }
}

应用程序组件.html

<div redItem>Item</div>
<div blueItem>Item</div>
<div blueItem>Item</div>
<div blueItem>Item</div>
<div redItem>Item</div>

<h2>Colors of the above directives</h2>
<ul>
  <li *ngFor="let color of itemColors">{{color}}</li>
</ul>

这里有一个堆栈闪电战在行动中展示这种行为。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

具有多种内容类型的 ContentChildren 的相关文章

随机推荐