@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>
这里有一个堆栈闪电战在行动中展示这种行为。