Angular12 ESLint要求用@HostBinding替换host元数据属性的实现方案咨询
问题解答
原有改写的错误说明
你之前的改写是不正确的,核心问题有两个:
@HostBinding的入参不需要加[]包裹,直接写对应的宿主属性/类名即可- 你直接把表达式写为固定字符串赋值给变量,不会随组件状态动态计算,完全无法实现原来的动态切换class的效果
正确改写步骤
1. 调整基础导入
先修改@angular/core的导入语句,引入HostBinding装饰器:
import { Component, Input, OnInit, ChangeDetectorRef, OnDestroy, HostBinding } from '@angular/core';
2. 移除原有host配置
删除@Component配置项里的整个host字段。
3. 组件类中添加动态计算的HostBinding属性
在MenuItemComponent类内部添加两个带@HostBinding装饰的getter属性,和原有host逻辑完全等价:
@HostBinding('class.active-menuitem') get isActiveMenuItem(): boolean { return (this.selectedKey && this.app.isHorizontal()) || (this.active && !this.app.isHorizontal()) || (this.active && !this.root && this.app.isHorizontal()); } @HostBinding('class.active-rootmenuitem') get isActiveRootMenuItem(): boolean { return this.active && this.root && this.app.isHorizontal(); }
使用getter的原因是每次组件触发变更检测时,都会自动重新计算返回值,实时同步到宿主元素的class上,和原有host元数据的运行效果完全一致,同时符合ESLint规则要求。
内容的提问来源于stack exchange,提问作者nop
相关产品推荐
相关产品推荐

