【问题标题】:Angular2 set style attributeAngular2设置样式属性
【发布时间】:2019-10-15 22:45:46
【问题描述】:

我正在尝试使用 angular 8 中的变量设置样式属性,但我无法让它工作。

    <ng-container *ngFor="let appointmentSlot of timeslots; let i = index">
        <div ngxSlickItem class="cards-slot slick-slide animation-show-slide-up"
          style='{{"--animation-delay:" + i}}'>
        </div>
    </ng-container>

谁能解释为什么样式属性没有打印?

似乎无法绑定该属性,因为它不安全。还是可以打印吗?

我发现这行得通:

  constructor(private sanitizer: DomSanitizer){}      

  getStyling(index: number) { 
    const styleAttribute = "--animation-delay: " +  index;
    return this.sanitizer.bypassSecurityTrustStyle(styleAttribute);
  }

【问题讨论】:

  • 您是否尝试过绑定到NgStyleangular.io/api/common/NgStyle
  • 我确实需要 style="--animation-delay: 1" 出现在标签中,这样我的 css 才能把它捡起来

标签: angular attributes interpolation


【解决方案1】:

可能是语法问题。您可以查看this demo,其中有样式用法示例,ngStylengClass。 hth

【讨论】:

    【解决方案2】:

    可以使用函数调用来建立您的样式,如下所示:

    HTML:

    <ng-container *ngFor="let appointmentSlot of timeslots; let i = index">
        <div ngxSlickItem class="cards-slot slick-slide animation-show-slide-up"
          [ngStyle]="getStyling(i)">
        </div>
    </ng-container>
    

    打字稿:

    getStyling(index: number) { 
        return { '--animation-delay': index } 
    } 
    

    【讨论】:

    • 那行不通。我确实需要style="--animation-delay: 1" 出现在标签中,这样我的css 才能接收到它。
    【解决方案3】:

    返回字符串似乎不安全,因此未打印。您可以使用以下命令否决:

     constructor(private sanitizer: DomSanitizer){}      
    
      getStyling(index: number) { 
        const styleAttribute = "--animation-delay: " +  index;
        return this.sanitizer.bypassSecurityTrustStyle(styleAttribute);
      }
    

    【讨论】:

      猜你喜欢
      • 2017-05-18
      • 2022-01-06
      • 2014-10-17
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-03
      相关资源
      最近更新 更多