【问题标题】:Css styles are not applied dynamical using [style.width.%] or [ngStyle] in Angular Material在 Angular 材质中使用 [style.width.%] 或 [ngStyle] 不会动态应用 Css 样式
【发布时间】:2020-07-14 09:51:12
【问题描述】:

我正在使用返回函数来调用和html

.ts 中的返回函数

 GetHtmlString(user) {
    return `
        <div class="custom-progressbar">
          <div *ngIf="user.HFPassed > 0"  [ngStyle]= "{ 'width':GetFlexValue(user.HFPassed, user) }" class="stat-bar bar-pass"></div>
      <div *ngIf="user.HFInProgress > 0" [style.width]="GetFlexValue(user.HFInProgress, user)" class="stat-bar bar-inprogress"></div>
      <div *ngIf="user.HFTodo > 0" [ngStyle]= "{ 'width':GetFlexValue(user.HFTodo, user) }" class="stat-bar bar-todo"></div>
      <div *ngIf="user.HFExpiring > 0" [style.width]="GetFlexValue(user.HFExpiring, user)" class="stat-bar bar-expiring"></div>
      <div *ngIf="user.HFExpired > 0" [style.width]="GetFlexValue(user.HFExpired, user)" class="stat-bar bar-expire"></div>
      <div *ngIf="user.HFFail > 0" [style.width]="GetFlexValue(user.HFFail,user)" class="stat-bar bar-fail"></div>
        </div>`;
  }

我简单地在GetFlexValue(user.HFPassed, user) 中设置了一些值,比如50,当我检查上面的div 时,我仍然没有得到宽度属性

简单的场景是我在我的 angualr 材料表中创建该 html,并在我的 td 中调用该函数来插入 html。 [ngStyle][style.width] 都用过,但没用...

我正在使用 Angular Material 也尝试了所有解决方案形式 Dynamically updating css in Angular 2

【问题讨论】:

    标签: angular angular-material


    【解决方案1】:

    请使用 [ngStyle],这会将包含元素的宽度设置为表达式返回的百分比值。

    GetHtmlString(user) {
        return `
            <div class="custom-progressbar">
              <div *ngIf="user.HFPassed > 0" [ngStyle]="{'width.%': GetFlexValue(user.HFPassed, user)"></div>
            </div>`;
      }
    

    参考链接 - https://angular.io/api/common/NgStyle

    【讨论】:

      【解决方案2】:

      实际上你并没有调用 GetFlexValue 函数,因为这是完整的字符串。

      此外,您需要在使用前清理此 html。

      import { DomSanitizer } from '@angular/platform-browser';
      

      这样做使用如下:

      getHtmlString(user) {
        return this.sanitized.bypassSecurityTrustHtml(`
              <div class="custom-progressbar">
                <div *ngIf="user.HFPassed > 0"
                style="width:` + this.GetFlexValue(user.HFInProgress, user) + `px"></div>
              </div>`);
      }

      这里是堆栈闪电战link

      【讨论】:

      • 试过但没用:(
      • 现在添加链接。
      【解决方案3】:

      [style.width.%]="GetFlexValue()"怎么样

      即 HTML 文件

      <div class="box" [style.width.%]="GetFlexValue()" ></div>
      

      组件文件

      export class AppComponent  {
        constructor(){}
      
        GetFlexValue(){
          return 50;
        }
      }
      

      stackblitz:https://stackblitz.com/edit/angular-ncr4nf

      【讨论】:

        猜你喜欢
        • 2019-04-30
        • 2020-02-07
        • 2020-10-05
        • 1970-01-01
        • 1970-01-01
        • 2018-07-18
        • 2021-05-07
        • 1970-01-01
        • 2016-01-11
        相关资源
        最近更新 更多