java开发公共组件调用平台,从Angular 8的父组件中调用动态子组件中的公共接口方法...

本文探讨如何在组件设计中避免直接继承接口,通过将接口转换为抽象类并使用`useExisting`和`InjectionToken`,实现组件间的逻辑统一。同时介绍了ViewChildren装饰器在管理父组件对子组件操作的应用。
摘要由CSDN通过智能技术生成

是的,这很棘手。您的所有子组件都继承了基本接口。有一种实现方法。但是,您将需要调整所有组件类型并将接口更改为抽象类。不用担心,如果它是一个没有定义逻辑的抽象类,它的作用与接口相同,您可以使用implements,但是通过这种方式,您无需创建InjectionToken:

export abstract class ComponentActions {

resetComponent(): void;

}

如果不能,或不想使其成为接口,请执行以下操作:

export const ComponentActionsToken = new InjectionToken('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

resetComponent(): void {

this.children?.forEach((child) => child.resetComponent);

}

}

如果使用注入令牌,则必须将ComponentActions中的ViewChildren值更改为ComponentActionsToken

就这些。但是请注意,这是未经测试的代码,但是应该可以使用。如果没有,请让我知道

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值