如果我们不能从父组件更改属性或操作它们,那么 @ViewChild 有什么用?

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

我有 2 个组成部分 - 家和关于。在两者中,我都注入了第三个(子)组件 - 心。现在,我正在使用来自 'home component' 的 @viewChild 操纵 hearts 中 'age' 属性 的值(默认设置为“23”)。我看到 'home Component' 中的值似乎发生了变化,但 '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;

快照(点击按钮)

您有两个不同的 <app-heart></app-heart> 实例,因此它们将保持自己的状态,这意味着其中一个实例的更改不会影响另一个实例。

如果您使用 @Input()-装饰器,情况也是如此,该值只会在您使用它的实例上更新。

使用 @Input()-装饰器时,您不必像使用 @ViewChild()-装饰器那样显式设置所需的值。

当您使用 @Input() 而不是 @ViewChild()

时,您也在解耦组件之间的关系