Angular 8中对应AngularJS的ng-attr-style属性的等效实现是什么
动态宽度绑定实现方案
Angular 8 已废弃AngularJS的ng-attr-style语法,可按照以下任意一种方式实现同等效果:
方案1:直接绑定style.width属性(最简写法)
<!-- 写法1:使用单位后缀语法糖,直接传入计算后的数值即可,自动拼接%单位 --> <div [style.width.%]="countersDtl.ServiceDone ? (countersDtl.SurveySubmittedInstant / countersDtl.ServiceDone * 100) : 0"> 内容 </div> <!-- 写法2:自行拼接单位 --> <div [style.width]="(countersDtl.ServiceDone ? (countersDtl.SurveySubmittedInstant / countersDtl.ServiceDone * 100) : 0) + '%'"> 内容 </div>
方案2:使用ngStyle指令(适合多样式同时绑定的场景)
首先确认对应业务模块已经导入CommonModule,这是ngStyle生效的前提:
// 对应模块的xxx.module.ts文件 import { CommonModule } from '@angular/common'; @NgModule({ imports: [ CommonModule, // 其他模块导入 ] }) export class YourBusinessModule { }
模板写法:
<div [ngStyle]="{ 'width': (countersDtl.ServiceDone ? (countersDtl.SurveySubmittedInstant / countersDtl.ServiceDone * 100) : 0) + '%' }"> 内容 </div>
样式不生效常见排查点
- 使用
ngStyle必须导入CommonModule,否则指令无法被识别,不会生效 - 必须处理
countersDtl.ServiceDone为0的边界场景,计算结果为NaN、Infinity时样式不会生效 - 若控制台出现样式安全拦截提示,优先使用带单位后缀的
[style.width.%]写法,无需额外处理安全消毒逻辑
内容的提问来源于stack exchange,提问作者A V
相关产品推荐
相关产品推荐

