首页 文章

Angular 4点击ngClass,如何仅适用于SELF但不适用于ng中的所有元素[重复]

提问于
浏览
0

这个问题在这里已有答案:

在Angular 2中,当我单击按钮时,它在ngFor循环内的每个“按钮”中添加了类“newstyle”...如何仅将ngClass条件绑定到元素本身?

<button [ngClass]="{'newstyle': isClicked }" (click)=" isClicked = !isClicked">Click button</button>

谢谢!

2 回答

  • 2

    试试这个:

    <button *ngFor="let thing of things" [class.newstyle]="currentThing === thing" (click)="currentThing = thing">Click button</button>
    

    您必须将currentThing添加为组件类的属性:

    export YourComponent {
        currentThing: any;
    }
    
  • 1

    类似的UseCase:遍历集合并为编辑后的 collection 中的 items 应用特定的类 item-updated .
    这部分是可选的,仅用于演示: [attr.title]="item.isDirty ? 'Item was updated' : null"

    html component

    <div *ngFor="let item of collection">
        <label>Name: {{item.name}}</label>
        <button class="btn"
             [ngClass]="{'item-updated' : item.isDirty}"
             [attr.title]="item.isDirty ? 'Item was updated' : null">
         Save
        </button>
    </div>
    

    Explanations: 仅当 item.isDirty 条件匹配时,该按钮才会收到特定的类 .

    在您的情况下,从问题,所有按钮绑定到相同的 isClicked 属性 . 因此,无论编辑哪一个,您的属性都会更改,所有其他按钮都会收到最新的类 .

    EDIT: 来自问题的代码段:

    <button [ngClass]="{'newstyle': isClicked }" (click)=" isClicked = !isClicked">Click button</button>
    

    Transformed

    HTML component

    <div *ngFor="let item of yourArray">
            <label *ngIf="item.isClicked">Item was Clicked: {{item.id}}</label>
            <button [ngClass]="{'newStyle' : !item.isClicked}" (click)="changeItemState(item)">Click button </button>
        </div>
    

    TS component

    import { Component, OnInit } from '@angular/core';
    
    @Component({
      selector: 'your-component',
      templateUrl: './your.component.html'  
    })
    export class YourComponent implements OnInit {
        public yourArray: any[];
    
        public ngOnInit(): void {
            this.yourArray = [
                {
                    id: 1,
                    name: 'First',
                    isClicked: false;
                }, 
                {
                    id: 2,
                    name: 'Second',
                    isClicked: false;
                }, 
                {
                    id: 3,
                    name: 'Third',
                    isClicked: true;
                }, 
            ];
        }
    
        public changeItemState(item: any): void {
            item.isClicked = !item.isClicked;
        }
    }
    

相关问题