setActive ngClass角度

时间:2020-05-12 07:48:21

标签: angular ng-class

嗨,我有一个简单的角度分量的问题,我要使用反应形式插入文本,然后在我想通过单击设置活动的一个元素后,但是当我单击一个元素时,使用ngFor循环文本元素达到活动类,这是我的模板。这是stack blitz link

<form [formGroup]="colorsForm">
  <div>
    <label for="colorName">Color Name</label>
      <input id="colorName" type="text" class="form-control" 
        formControlName="colorName" name="colorName"/>
  </div>
  <button  type="button"  (click)="addCorlo()">ADD</button>
</form>
<div
*ngFor="let color of colorsList; let i = index"
(click)="setActive(color)"
[ngClass]="{'active' : color.i === active?.i}"
>
<div
> ID {{ i }} - color {{ color.colorName }}<button (click)="delete(i)">DELETE</button></div>
</div>

这是我的ts

import { Component, VERSION } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, Validators } from '@angular/forms';


@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Set Active';
  colorsForm: FormGroup; // New Reactive Form
  colorsList: any[] = [];
  active: any;


  constructor(
    private fb: FormBuilder
  ) { }

  ngOnInit() {

    this.colorsForm = this.fb.group({
      colorName: [null]
    });

  }

  addCorlo() {
    if (this.colorsForm.valid) {
      let color = { 
        colorName: this.colorsForm.value.colorName,
      };
      this.colorsList.push(color);
    }
    this.colorsForm.reset();
   }


   delete(i: number) { 
    if (i > -1) {
        this.colorsList.splice(i, 1);
        console.log('ID',i)
        console.log('ARRAY',this.colorsList)
    }
    return this.colorsList;

  }

  setActive(color: any){
    console.log(color);
    this.active = color;
  }


}

2 个答案:

答案 0 :(得分:0)

您的检查不正确。在颜色或活动对象中没有名为i的属性。

就地,您可以直接比较对象

[ngClass]="{'active' : color === active}"

答案 1 :(得分:0)

[ngClass]="{'active' : color.colorName === active?.colorName}"

此检查需要特定于colorName。

相关问题