setActive ngClass angular

问题描述 投票:0回答:1

你好,我有一个简单的角度分量的问题,我正在使用反应形式插入文本,然后在我想通过单击设置活动的一个元素后,但是当我单击一个元素时,所有元素都将使用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;
  }


}

angular ng-class
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.