javascript - 如果我们无法从父组件更改属性或操作它们,那么 @ViewChild 有什么用呢?

标签 javascript angular components angular-directive viewchild

我有 2 个组件 - 主页和关于。在这两种情况下,我都注入(inject)了第三种(子)成分——心脏。现在,我使用“home 组件”中的 @viewChild 来操作心中“age”属性的值(默认设置为“23”)。我发现“home 组件”的值似乎发生了变化,但“about 组件”的值却没有变化。

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;

快照(单击按钮时)

enter image description here

最佳答案

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

如果您使用@Input(),情况也是如此。 -decorator,该值仅在您使用它的实例上更新。

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

当您使用@Input()时,您还解耦了组件之间的关系而不是@ViewChild()

关于javascript - 如果我们无法从父组件更改属性或操作它们,那么 @ViewChild 有什么用呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53648526/

相关文章:

javascript - 使用google脚本操作数据条件格式和数据验证

angular - D3,Typescript - 类型 'this' 的参数不可分配给类型 'BaseType' 的参数

javascript - Angular i18n 动态文本

Angular 2 : How to dynamically create ViewContainerRef

javascript - React Native 时间线 ListView

javascript - 具有多个独立对象的 requestAnimationFrame

Javascript 下拉菜单不适用于 iphone/ipad

javascript - D3 中的工具提示如何动态获取数据?

angular2将模型值绑定(bind)到单选按钮

使用经典 ASP 上传图片