Updating value in the child component , on value changes in the parent component

22,155

Solution 1

Values changes from parent to child components are reflected immediately. However, you can listen for value changes event in the child component. Read more about ngOnChanges

Here is an example on stackblitz

app.component.html

<hello name="{{ name }}"></hello>
<p>
  Start editing to see some magic happen :)
</p>

<app-child [data]="count"></app-child>

app.component.ts

import { Component, OnInit } from "@angular/core";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"],
})
export class AppComponent implements OnInit {
  name = "Angular";

  count = 0;

  constructor() {}

  ngOnInit(): void {
    setInterval(() => this.updateCount(), 1000);
  }

  updateCount(): void {
    this.count++;
  }
}

child.component.html

<p>{{data}}</p>

child.component.ts

import { Component, OnInit, OnChanges, Input, SimpleChanges } from "@angular/core";

@Component({
  selector: "app-child",
  templateUrl: "./child.component.html",
  styleUrls: ["./child.component.css"],
})
export class ChildComponent implements OnInit, OnChanges {
  @Input() data: any;

  constructor() {}

  ngOnInit() {}

  ngOnChanges(changes: SimpleChanges): void {
    console.log("value changed", this.data);
  }
}

Solution 2

Say this is your parent component.

    import { Component, ViewChild, AfterViewInit } from '@angular/core';        

    @Component({
        selector: 'app-root',
        templateUrl: './app.component.html'
    })
    export class AppComponent implements AfterViewInit{

        message = "hello again";
        friends:string[] = [];

        //will add friend to our list of friends array
        add(friend){
            if(friend.value){
                this.friends.push(friend.value);    
                friend.value = "";
            }
            console.log(this.friends);
        }

        ngAfterViewInit() {    
            
        }

    }

Parent Component UI

    <div>
        <input #friend type="text" placeholder="name of friend" />
        <button type="button" (click)="add(friend)">add friend</button>
    </div>

    <app-to-child message="List of friends" [friends]="friends"></app-to-child>   

Now child component

Use @Input decorator with fields in which you want to receive data from the parent component.

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

    @Component({
        selector: 'app-to-child',
        templateUrl: './to-child.component.html',
        styleUrls: ['./to-child.component.css']
    })
    export class ChildComponent implements OnInit {

      @Input() message:string;
      @Input() friends:string[];
      constructor() { }

      ngOnInit() {
      }

      //this will called when data is passed from parent to child.
      ngOnChanges(val){
          console.log("change detected");
          console.log(val);                
      }

   }

inside child.component.html

      <h5>CHILD COMPONENT</h5>
      <p>Message : {{message}}</p>
      <div *ngFor="let friend of friends"> {{friend}}</div>

You can learn more about component interactions here, a quick walk through.

Share:
22,155
Testing Anurag
Author by

Testing Anurag

Updated on November 09, 2021

Comments

  • Testing Anurag
    Testing Anurag over 2 years

    I am working in Angular ,where -

    • I am trying to Update value in the child component , on value changes in the parent component

      (as value is coming dynamically to the parent component from some other component) .

    How I tried

    • I tried to pass data from parent component to child component Using @Input decorator

    • using @Input value is passed just once when component loads and latter on value is not passed

    I am sharing my code below

    Parent component

    .html

    <app-banner [tournamentType]='tournamentType'></app-banner>
    

    .ts

    child component

    .ts file

    import { Component, OnInit , Input } from '@angular/core';
    import { ServicesService } from '../service/services.service';
    
    @Component({
      selector: 'app-banner',
      templateUrl: './banner.component.html',
      styleUrls: ['./banner.component.scss']
    })
    export class BannerComponent implements OnInit {
    
      @Input() tournamentType;
    
      sportsType : any = 1;
    
    
    
      constructor(private rest : ServicesService) { }
    
      ngOnInit() {
        console.log("this. is banner page" + this.tournamentType);
        alert('hello');
    
        this.loadDataFromApi(1);
      }
    
      loadDataFromApi(sportsType) {
    
         this.rest.getbanner(this.sportsType).then(res => {
           console.log('>>>$$$$$ banner >>>>>> $$$$$$$$$$');
           console.log('  @Input tournamentType; ====' + this.tournamentType );
           console.log(res);
    
         })
        console.log(sportsType);
      }
    }
    
  • gyc
    gyc over 5 years
    implement OnChanges