Search code examples
javascriptangularcomponentsangular-directiveviewchild

What is use of @ViewChild if we cannot change properties or manipulate them from Parent Component?


I got 2 components - home & about. In both I inject a third (child) compnonent - hearts. Now I am manipulation the value of 'age' property in hearts (set to default as '23') using @viewChild from 'home component'. I see that value seems changed in view of 'home Component' but not in 'about component'.

My Questions:

  1. How does the value seem to be changed in 1st component but not in second -- this means modal or value does not get changed in 'hearts component' (that's why not updated in About component) -- but then how does this seem to get changed to '33' in home component?

  2. If the value of 'child component property' cannot be changed via parent using @viewChild -- then what the use of accessing from Parent. Why then not directly just use the @input decorator -- it does better job. Isn't it?

1 - app.component.html

<app-home></app-home>
<app-about></app-about>

2a - home.component.html

<app-heart #ref1></app-heart>
<button (click)="alpha()">click</button>

2b - home.component.ts

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

@ViewChild('ref1') ref1: HeartComponent;

alpha(){
  this.ref1.age = 33;
}

3 - about.component.html

<app-heart></app-heart>

4 - heart.component.ts

age = 23;

Snapshot (on click of button)

enter image description here


Solution

  • You have two different instances of <app-heart></app-heart>, so they will keep their own states, which means a change in one of the instances does not affect the other.

    The same goes if you use the @Input()-decorator, the value only updates on the instance you use it on.

    When using an @Input()-decorator, you do not have to set the desired value explicit as you do using the @ViewChild()-decorator.

    You are also decoupling the relation between components when you use @Input() instead of @ViewChild()