angular - 从Angular 8中的父组件调用动态子组件中的通用接口方法
问题描述
我需要从 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
}
}
如果您使用注入令牌,则必须ComponentActions
将提供属性中的值更改为ComponentActionsToken
现在感觉就像,根据您的模板,您可以ComponentActions
在父模板中有多个实例。因此,您需要一些逻辑来确定您要对哪个执行操作。但我想你已经做到了。
除此之外,您还想同时对所有组件执行此操作。所以这就是ViewChildren
装饰器出现的地方:
@Component({
selector: 'parent'
})
export class ParentComponent {
@ViewChildren(ComponentActions)
children?: QueryList<ComponentActions>
resetComponent(): void {
this.children?.forEach((child) => child.resetComponent());
}
}
如果您使用的是注入令牌,则必须将 to 中的ComponentActions
值更改ViewChildren
为ComponentActionsToken
就这样。但请注意,这是一些未经测试的代码,但它应该可以工作。如果没有,请告诉我
推荐阅读
- javascript - Javascript 类属性被初始化为未定义
- python - 使用 selenium 使用 jscript _doPostBack 链接显示“下一个”搜索结果
- mysql - 我如何显示当我使用 vb.net 加载我的第一个表单时显示的第一个面板
- amazon-web-services - AWS Cloud9:在本地引用 Lambda 层
- python - 在 django 中使用 google recaptcha V3 的最佳方式
- javascript - 使用索引拼接list.filter中的文件时得到不正确的文件名
- java - Google Cloud Endpoints - API 方法仅在删除用户参数时成功调用
- php - 未定义属性:Blog::$pagination
- python - 从本地工作目录调用 Python 函数
- android - Android countDownTimer 只工作一次