Search code examples
angular6angular-ngmodelngforngmodel

How to fix ngFor each row clickStatus value change when click on that row only


  • am new for this angular6
  • i have done code for generating div with *ngFor

  • i have tried to click on each row (span text) then that row Boolean value should effect but its changing the other row values also.

  • my goal is when click on span row then that clicked row value should change.

  • component.ts

    import { Component, NgModule, VERSION, Input, OnInit } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; @Component({ selector: 'my-app-test', template: <div> <h1>Hello</h1> <div id="{{obj.name}}" *ngFor="let obj of objList"> <span id="{{obj.name}}" (clickStatus)='false' (click)='changeColor($event, obj)'>{{obj.text}}</span> <!-- [(ngModel)]="clickStatus" ngDefaultControl --> </div> </div> , }) export class TestComponent implements OnInit { name: string; @Input() clickStatus: boolean = false; @Input() objList: any[] = []; objData = { name : 'name', text : 'text' }; list = []; constructor() { this.name =Angular! v${VERSION.full}; } ngOnInit() { for (let i = 0; i < 10; ++i) { this.objData = { name : 'name' + i, text : 'text' + i }; this.list.push(this.objData); } console.log('data .. ', this.list); this.objList = this.list; } changeColor(event, obj) { console.log('event...', event.target as Element); console.log('obj and clickstatus ...', obj, this.clickStatus); if (this.clickStatus) { console.log('click status in if true', this.clickStatus); } else { console.log('click status in else false', this.clickStatus); } this.clickStatus = !this.clickStatus; } }

  • My code Editor : Code


Solution

  • Well, your using the same ngmodel for all your rows ofcorse it will change everyone. If you want to do it like this make it as Array.

      <div id="{{obj.name}}" *ngFor="let obj of objList;let i = index">
        <span id="{{obj.name}}" [(ngModel)]="clickStatus[i]" ngDefaultControl (click)='changeColor($event, obj,i)'>
          {{obj.text}}</span>
      </div>
    
     public clickStatus:Array<boolean>= new Array(this.objList.length);
      changeColor(event, obj,i) {
        console.log('event...', event.target as Element);
        console.log('obj and clickstatus ...', obj, this.clickStatus);
        if (this.clickStatus[i]) {
          console.log('click status in if true', this.clickStatus[i]);
        } else {
          console.log('click status in else false', this.clickStatus[i]);
        }
        this.clickStatus[i] = !this.clickStatus[i];
      }
    

    something like this should work.