代码之家  ›  专栏  ›  技术社区  ›  Chris

基于动态数据的ngstyle设置

  •  0
  • Chris  · 技术社区  · 6 年前

    我有一个包含path元素的svg。我希望根据名为 shirts .

    <path class="st2" style="stroke-width:2.0;" [ngStyle]="myStyle(4)" d="M11.5,315....315.9z"/>
    

    我的 myStyle 功能是:

    myStyle(p): Object {
        return {
            fill: this.shirts[p]
        }
    }  
    

    在我的组件中,我有:

    shirts: any = [];
    
    setShirts(shirts) {
        this.shirts = shirts;
    }
    

    我正在打电话 setShirts 设置的值 衬衫

    我的问题是,在SVG显示时 衬衫 是空的。一秒钟后 衬衣 踢进 衬衫 设置为一系列颜色。

    我如何得到 我的风格 检查 衬衫 只有在颜色由 衬衣 ?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Prachi    6 年前

    您可以在ngoninit()中调用函数,也可以尝试:

    在HTML中:

    <path *ngIf="isListLoaded" class="st2" style="stroke-width:2.0;" [ngStyle]="myStyle(4)" d="M11.5,315....315.9z"/>
    

    在TS中:

    isListLoaded :any = false;
    
    setShirts(shirts) {
        this.shirts = shirts;
        this.isListLoaded = true;
    }
    

    更新的 :

    在player.ts中导入changedectorref

    import { ChangeDetectorRef } from '@angular/core';
    

    在player.ts中注入并实例化它

    constructor(private ref: ChangeDetectorRef) { 
    }
    

    最后

    setShirts(shirts) {
        this.shirts = shirts;
        this.isListLoaded = true;
        this.ref.detectChanges();
    }