【问题标题】:How to use [ngStyle] to apply styling to a selected element in *ngFor?如何使用 [ngStyle] 将样式应用于 *ngFor 中的选定元素?
【发布时间】:2021-07-05 10:42:34
【问题描述】:

我将有多个按钮,并且需要使用表单来设置按钮的样式。每个按钮都应该能够获得自己的特定样式。在下面的示例中,我尝试单击列表中的一个按钮以将其选中,然后单击一个单独的按钮以使用 [ngStyle] 将样式应用于所选按钮。到目前为止,一切似乎都在工作,除了通过 [ngStyle] 的新样式没有被应用而且我没有看到任何错误。

<div *ngFor="let button of buttons;">
    <button class="button" [class.selected]="button === selectedButton" [ngStyle]="buttonStyles" (click)="selectButton(button)">{{button.text}}</button>
</div>

<button (click)="changeNgStyle()">changeNgStyle</button>
selectedButton?;

selectButton(button): void {
    this.selectedButton = button;
}

changeNgStyle() {
    this.selectedButton.buttonStyles = {
        'color':'blue', 
        'font-weight':'bold',
        'background-color': 'red'
    };
}

【问题讨论】:

    标签: angular ng-style


    【解决方案1】:

    由于我在您的 ts 代码中看不到任何 buttonStyles 声明,请尝试以下操作:

    [ngStyle]="selectedButton?.buttonStyles"
    

    所以,你的 html 应该是这样的:

    <button class="button" [class.selected]="button === selectedButton" [ngStyle]="selectedButton?.buttonStyles" (click)="selectButton(button)">{{button.text}}</button>
    

    【讨论】:

      【解决方案2】:

      问题不是很清楚,但似乎样式包含在selectedButton 变量的buttonStyles 属性中。那么ngStyle不应该绑定到selectedButton.buttonStyles吗?

      试试下面的

      <button 
        class="button" 
        [class.selected]="button === selectedButton" 
        [ngStyle]="selectedButton.buttonStyles" 
        (click)="selectButton(button)"
      >{{button.text}}</button>
      

      【讨论】:

        猜你喜欢
        • 2020-09-15
        • 2019-12-12
        • 2016-09-23
        • 1970-01-01
        • 2017-10-18
        • 2020-01-24
        • 2020-10-05
        • 2012-01-29
        • 2020-02-07
        相关资源
        最近更新 更多