我需要从一个接口调用通用方法,该接口在Angular的父级组件的动态子级组件中实现。我的父html组件将如下所示:
parent.component.html:
<div *ngFor = "let config of childConfigs">
<div *ngIf = " config.type == 'a' ">
<child-a [config]="config"></child-a>
</div>
<div *ngIf = " config.type == 'b' ">
<child-b [config]="config"></child-b>
</div>
.
.
<div *ngIf = " config.type == 'n' ">
<child-n [config]="config"></child-n>
</div>
</div>
<button (click)="resetComponent()"> Reset</button>
假设有一个接口'ComponentActions',其中包含方法resetComponent()并且所有子组件都实现了它。子组件示例结构将是这样]
child-a.component.ts:
export class ChildAComponent implements ComponentActions {
@Input() config;
resetComponent(){
// do something
}
}
如何通过单击父级按钮将这种方法引入子级组件中?
是的,这很棘手。您的所有子组件都继承了基本接口。有一种实现方法。但是,您将需要调整所有组件类型并将接口更改为抽象类。不用担心,如果它是一个没有定义逻辑的抽象类,它的作用与接口相同,您可以使用implements
,但是通过这种方式,您无需创建InjectionToken
:
export abstract class ComponentActions {
resetComponent(): void;
}
如果不能,或不想使其成为接口,请执行以下操作:
export const ComponentActionsToken = new InjectionToken<ComponentActions>('component actions');
有了这个,您可以为所有子组件提供以下内容,因此对于您将每个子组件作为useExisting
放置的是相应的子类:
@Component({
selector: 'child-x',
providers: [{ provide: ComponentActions, useExisting: ChildXComponent }]
})
export class ChildXComponent implements ComponentActions {
resetComponent(): void {
// do something
}
}
@Component({
selector: 'child-y',
providers: [{ provide: ComponentActions, useExisting: ChildYComponent }]
})
export class ChildYComponent implements ComponentActions {
resetComponent(): void {
// do something
}
}
如果使用注入令牌,则必须将Provide属性中的ComponentActions
值更改为ComponentActionsToken
现在感觉,根据您的模板,您可以在父模板中具有ComponentActions
的多个实例。因此,您需要一些逻辑来确定要对其执行操作的逻辑。但是我想你已经准备好了。
此外,您还希望同时对所有组件执行此操作。所以这是ViewChildren
装饰器到位的地方:
@Component({
selector: 'parent'
})
export class ParentComponent {
@ViewChildren(ComponentActions)
children?: QueryList<ComponentActions>
resetComponent(): void {
this.children?.forEach((child) => child.resetComponent);
}
}
如果使用注入令牌,则必须将ComponentActions
中的ViewChildren
值更改为ComponentActionsToken
就这些。但是请注意,这是未经测试的代码,但是应该可以使用。如果没有,请让我知道