【问题标题】:ngStyle not getting appliedngStyle 没有被应用
【发布时间】:2017-11-27 06:28:59
【问题描述】:

在我的 Angular 5 应用程序中,[ngStyle] 没有扩展到样式属性。我只看到 ng-reflect-ng-style。这以前可以工作。最近对 Angular 或 Angular-cli 的更新有什么变化吗?

这是模板:

<div *ngIf="ready" class="card" [ngStyle]="dimensions">
</div

这是生成的 HTML:

<div _ngcontent-c6="" class="card ng-tns-c6-1" ng-reflect-ng-style="[object Object]">

</div>

预期,尺寸 = {width: '240px'}:

<div _ngcontent-c6="" class="card ng-tns-c6-1" ng-reflect-ng-style="[object Object]" style="width:240px">

</div>

【问题讨论】:

  • 请转载。它对我很有效

标签: angular angular-cli


【解决方案1】:

可以直接在模板中使用-

[ngStyle]="{'width.px': 200}"

dimensions = {'width.px': 200};
<div *ngIf="ready" class="card" [ngStyle]="dimensions">
</div

【讨论】:

    【解决方案2】:

    你也可以尝试如下:

    <div *ngIf="ready" class="card" [ngStyle]="setStyles()">
    </div>
    
    public setStyles(): any {
        let styles = {            
            'width': '200px'
        };      
        return styles;
    }
    

    [ngStyle]="{'width': '200px'}"
    

    【讨论】:

      【解决方案3】:

      从今天开始,使用 Angular > 11,您必须像下面这样清理此类信息

      <div [attr.style]="dimensions | safeStyle"> </div>
      

      safeStyle

      @Pipe({ name: 'safeStyle' })
      export class SafeStylePipe implements PipeTransform {
        constructor(private sanitizer: DomSanitizer) {}
        transform(value) {
          return this.sanitizer.bypassSecurityTrustStyle(value)
        }
      }
      

      this thread找到解决方案

      【讨论】:

        猜你喜欢
        • 2021-01-23
        • 1970-01-01
        • 2020-12-16
        • 2019-12-12
        • 2021-06-20
        • 2012-09-30
        • 2015-04-13
        • 2018-08-23
        • 2019-04-30
        相关资源
        最近更新 更多