我有 2 个组件 - 主页和关于。在这两种情况下,我都注入(inject)了第三种(子)成分——心脏。现在,我使用“home 组件”中的 @viewChild 来操作心中“age”属性的值(默认设置为“23”)。我发现“home 组件”的值似乎发生了变化,但“about 组件”的值却没有变化。
My Questions:
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?
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()
,情况也是如此。 -decorator,该值仅在您使用它的实例上更新。
使用 @Input()
时-decorator,您不必像使用 @ViewChild()
那样显式设置所需的值-装饰器。
当您使用@Input()
时,您还解耦了组件之间的关系而不是@ViewChild()
关于javascript - 如果我们无法从父组件更改属性或操作它们,那么 @ViewChild 有什么用呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53648526/