0

Question: why are the changed to the object in the parent not displaying in the child component?

blah

I am having difficulty detecting changing values in an object in a parent component when it is displayed in the child component.

The parent component template has buttons to increase values.

<div class="container root">
  <div class="row">
    <div class="col-md-12 col-xs-12">
      <h1>
       {{title}}
      </h1>
      <button (click)="funct1()" class="btn btn-success btn-lg">A ++</button>
      <button (click)="funct2()" class="btn btn-success btn-lg">B ++</button>
      <button (click)="funct3()" class="btn btn-success btn-lg">C ++</button>
      <button (click)="funct4()" class="btn btn-success btn-lg">D ++</button>
      <p *ngFor="let item of details"><strong>name:</strong> {{item.name}}, <strong>id:</strong> {{item.value}}</p>
    </div>
    <div class="row child">
      <div class="col-md-6 col-md-6">
        <app-child [data]="details">loading child component</app-child>
      </div>
    </div>
  </div>
</div>

The app.component.ts file,

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Root component!';
  value1: number = 0;
  value2: number = 0;
  value3: number = 0;
  value4: number = 0;
  details: {name: string, value:number}[]=[]

  arrayBuild(){
     this.details = [{name: 'A', value: this.value1}, {name: 'B', value: this.value2}, {name: 'C', value: this.value3}, {name: 'D', value: this.value4}];
  }
  funct1(){
    this.value1++;
    this.arrayBuild();
  }
  funct2(){
    this.value2++;
    this.arrayBuild();
  }
  funct3(){
    this.value3++;
    this.arrayBuild();
  }
  funct4(){
    this.value4++;
    this.arrayBuild();
  }
}

child.component.ts

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

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit, OnChanges {
  @Input() data: {name: string, value: number}[] = [];

  constructor() { }

  ngOnInit() {
  }

  ngOnChanges(){

  }
}

The child.component.html

<div class="child">
  <h3>Child Component!</h3>
  <p *ngFor="let element of data"><strong>name:</strong> {{element.name}}, <strong>id:</strong> {{element.id}}</p>
</div>

I think this is going to have something to do with lifecycle hooks, which I am only vaguely familiar with.

The code on github here. Thanks,

Shane G
  • 3,129
  • 10
  • 43
  • 85

0 Answers0