如何从抽象基类中访问组件上挂载的attribute directive属性指令
实现方法
你可以通过 Angular 依赖注入能力,在基类中获取宿主元素上挂载的指令实例,具体操作如下:
步骤1:修改抽象基类构造函数
在基类的构造函数中声明需要注入的IdentityBoxDirective,搭配@Optional()装饰器兼容部分组件未挂载该指令的场景,搭配@Host()限制只查找当前组件宿主上的指令实例,避免误注入父级同类型指令:
import { Optional, Host } from '@angular/core'; import { IdentityBoxDirective } from './your-path/identity-box.directive'; export abstract class BaseComponentClass{ constructor( @Optional() @Host() protected identityBox: IdentityBoxDirective ) {} // 基类中可直接通过this.identityBox访问指令实例 sampleMethod() { if (this.identityBox) { // 调用指令属性/方法 this.identityBox.doSomething(); } } }
步骤2:子类组件传递注入实例
所有继承BaseComponentClass的自定义组件,需要在自身构造函数中注入指令实例,并传递给父类构造函数即可:
import { IdentityBoxDirective } from './your-path/identity-box.directive'; export class ImageComponent extends BaseComponentClass implements OnInit, OnChanges { constructor( @Optional() @Host() identityBox: IdentityBoxDirective ) { // 将指令实例传递给基类 super(identityBox); } }
补充说明
- 如果你能保证所有继承基类的组件都会挂载
identityBox指令,可以去掉@Optional()装饰器,此时如果组件未挂载指令会直接抛出注入错误,更便于前期调试 - 无需修改现有模板调用逻辑,原有
<app-ofc-image identityBox></app-ofc-image>的写法完全兼容
内容的提问来源于stack exchange,提问作者calbear47
相关产品推荐
相关产品推荐

