Home > Blockchain >  How to update the child component value on change?
How to update the child component value on change?

Time:10-12

since I am using spread operator, my changes not reflecting to child component. what is the correct way to handle this?

code in child:

import {
  Component,
  Input,
  OnChanges,
  OnInit,
  SimpleChange,
} from '@angular/core';

@Component({
  selector: 'my-child',
  template: `
  <h1>{{Nwname}}</h1>
  <ul>
    <li *ngFor="let item of updatedRows">{{item.TelephoneNo}}</li>
  </ul>
  `,
  styles: [],
})
export class ChildComponent implements OnInit {
  @Input() Nwname;
  @Input() Nwrows;
  updatedRows;
  ngOnInit() {
    const rows = [...this.Nwrows];
    this.updatedRows = rows; //updateds only once
  }
}

Live Demo

CodePudding user response:

In the example, you are assigning a new array to this.rows, so that will trigger change detection, I think your problem is that you are overring the main dataset, can try the below code

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  name = 'Angular';
  rows;
  dataset = [
    {
      AbbottPersonnel: 'Daavid Malan',
      TelephoneNo: '123',
      ActivationStatus: 'Inactive',
    },
    {
      AbbottPersonnel: 'Sharon Grant',
      TelephoneNo: '122',
      ActivationStatus: 'Active',
    },
    {
      AbbottPersonnel: 'Yegeny Kafalnikov',
      TelephoneNo: '122',
      ActivationStatus: 'Active',
    },
    {
      AbbottPersonnel: 'Masake Akase',
      TelephoneNo: '123',
      ActivationStatus: 'Active',
    },
  ];

  constructor() {
    this.rows = [...this.dataset]
  }

  updateSearch(Nwvalue) {
    if (!Nwvalue) {
      console.log('now vlaue', this.copy);
      this.rows = [...this.dataset];
      return;
    }
    const filtered = this.dataset.filter((record) => {
      return Object.values(record).some((value) => value.includes(Nwvalue));
    });
    console.log('filtered', filtered);
    this.rows = filtered;
  }
}

CodePudding user response:

This has nothing to do with using spread or not. I would also suggest against forcing change detection.

Your issue is that you don't have ngOnChanges set up. So NgOnInit fires only once, as it should. If you want it to respond to changes in the Input then implement OnChanges

Code:

ngOnChanges(changes: SimpleChanges) {
    console.log('On Changes: ', changes);

    if (changes && changes.rows && changes.rows.currentValue) {
      this.localRows = changes.rows.currentValue;
    }
  }

if for some reason above complains about using the . approach to changes, then you can also do changes['rows']. Stackblitz: https://stackblitz.com/edit/angular-uks7uf?file=src/app/child/child.component.ts

I suggest you also look into the different Angular life cycle hooks like OnInit, AfterViewInit, etc.

  • Related