我有一个组件 HelloComponent。该组件采用 MyButtonDirective 类型的所有内容子项,并为每个子项呈现一个按钮标签。
@Component({
selector: 'hello',
template: `
<p>{{buttons.length}}</p>
<button *ngFor="let b of buttons" (click)="b.onClick()">{{b.text}}</button>`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
@ContentChildren(MyButtonDirective, {descendants: true}) buttons: QueryList<MyButtonDirective>;
}
@Directive({
selector: 'my-button'
})
export class MyButtonDirective {
@Input() text: string;
@Output() click: EventEmitter<any> = new EventEmitter<any>();
onClick() {
console.log('my-button clicked');
this.click.emit();
}
}
有没有办法可以从 MyButtonDirective 子类化或派生来创建一个新的指令 och 组件,该组件将包含在 HelloComponent 的 contentchildren 中?
<hello>
<my-button></my-button>
<my-button></my-button>
<extra-button></extra-button> <-- How can this be included in contenchildren of Hello?
</hello>
我做了一个斯塔克闪电战 https://stackblitz.com/edit/angular-custom-sub-components?file=src%2Fapp%2Fhello.component.ts为了这。
只是为了简化,我创建了并且AbstractButton
abstract class AbstractButton {
text: string;
abstract onClick();
}
现有的MyButtonDirective
& ReplayButton
现在延长AbstractButton
@Directive({
selector: 'my-button',
providers: [{provide: AbstractButton, useExisting: forwardRef(() => MyButtonDirective)}]
})
export class MyButtonDirective extends AbstractButton {
...
}
The HelloComponent
除了类型保持不变ContentChildren
...
export class HelloComponent {
@Input() name: string;
@ContentChildren(AbstractButton, {descendants: true}) buttons: QueryList<AbstractButton>;
}
我也看到你有ExtraButtonComponent
有模板<my-button>
,但我不确定这是否有效,因为它位于另一个组件内并且是该组件的子组件
查看StackBlitz 演示在这里 https://stackblitz.com/edit/angular-custom-sub-components-gztc1t.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)