从Angular 8中的父组件调用动态子组件中的公共接口方法
我需要从接口调用一个公共方法,该接口在Angular中的父组件的动态子组件中实现。 我的父html组件将如下所示: parent.component.html:从Angular 8中的父组件调用动态子组件中的公共接口方法,angular,typescript,angular6,angular8,angular-dynamic-components,Angular,Typescript,Angular6,Angular8,Angular Dynamic Components,我需要从接口调用一个公共方法,该接口在Angular中的父组件的动态子组件中实现。 我的父html组件将如下所示: parent.component.html: <div *ngFor = "let config of childConfigs"> <div *ngIf = " config.type == 'a' "> <child-a [config]="config"></child-a> </div
<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>
如何通过从父级单击按钮将此方法包含到子组件中?对,这是一个棘手的问题。您的子组件都继承了一个基本接口。有一种方法可以实现这一点。但是,您需要调整所有组件类型,并将接口更改为抽象类。别担心,如果它是一个没有定义逻辑的抽象类,那么它的作用与接口相同,您可以使用
实现
,但这样您就不需要创建注入令牌
:
export abstract class ComponentActions {
resetComponent(): void;
}
如果不能或不想将其作为接口,请执行以下操作:
export const ComponentActionsToken = new InjectionToken<ComponentActions>('component actions');
如果您正在使用注入令牌,则必须将提供属性中的ComponentActions
值更改为ComponentActionsToken
现在,根据您的模板,您可以在父模板中拥有多个ComponentActions
实例。因此,您需要一些逻辑来确定要对哪个对象执行操作。但我想你已经准备好了
除此之外,您还希望同时对所有组件执行此操作。这就是ViewChildren
装饰器的位置:
@Component({
selector: 'parent'
})
export class ParentComponent {
@ViewChildren(ComponentActions)
children?: QueryList<ComponentActions>
resetComponent(): void {
this.children?.forEach((child) => child.resetComponent());
}
}
@组件({
选择器:“父级”
})
导出类ParentComponent{
@ViewChildren(组件操作)
儿童?:查询列表
resetComponent():void{
this.children?.forEach((child)=>child.resetComponent());
}
}
如果您正在使用注入令牌,则必须将ViewChildren
中的ComponentActions
值更改为ComponentActionsToken
就这些。请注意,这是一段未经测试的代码,但它应该可以工作。如果没有,请告诉我非常感谢。它对我有用,只是做了些小小的修改!!再次非常感谢@毗瑟奴彭南很高兴我能帮上忙!您需要做哪些修改?我可以更新我的答案,以帮助未来的读者
@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
}
}
@Component({
selector: 'parent'
})
export class ParentComponent {
@ViewChildren(ComponentActions)
children?: QueryList<ComponentActions>
resetComponent(): void {
this.children?.forEach((child) => child.resetComponent());
}
}