父变量未在 Angular 的子组件中更新

Yas*_*aga 6 input typescript angular

我在父组件中有一个这样的变量:

父组件

export class ParentComponent {
    
  variable = {};
  varExample = false;
  @ViewChild('child') child: ChildComponent;
  
  someFunction () {
    this.variable['id'] = {};
    for (let i = 0; i < 10; i++) {
      this.variable['id'][i] = i*2; 
    }
    this.varExample = true;
  }

  otherFunction () { // called when i click a button
    this.someFunction ();
    
    console.log(this.child.variable); // {}
    console.log(this.child.varExample); // true
    this.child.initVars();
  }
}
Run Code Online (Sandbox Code Playgroud)

父 HTML

<app-child #child [variable]="variable" [varExample]="varExample"></app-child>
Run Code Online (Sandbox Code Playgroud)

子组件

export class ChildComponent {
  @Input() variable: any;
  @Input() varExample: boolean;

  initVars() {
    console.log(this.variable); // {}
    console.log(this.varExample); // true
  }
}
Run Code Online (Sandbox Code Playgroud)

这只是我的实现的一个例子,是的,我有所有导入。

在那些console.log(this.variable)我得到一个空对象({}),但 varExample 仍然工作正常。为什么 childvariable总是空的,Angular 没有检测到这种类型的 Objects ( {}) 的变化?

有人能帮我吗?

Mic*_*l D 11

  1. 答案已经在问题里了。为varExample您重新分配它的值this.varExample = ...。但this.variable只是它的内容发生了变化。当底层引用没有改变时,Angular 将不会检测到它的变化。您可以使用@user2846469 的解决方案或使用扩展语法来调整值和内联引用。

家长

someFunction() {
  this.variable["id"] = {};
  for (let i = 0; i < 10; i++) {
    this.variable = {
      ...this.variable,
      id: {
        ...this.variable["id"],
        [i]: i * 2
      }
    };
  }
  this.varExample = true;
}
Run Code Online (Sandbox Code Playgroud)
  1. 使用@ViewChild来触发另一个组件的功能是不优雅的。OnChanges相反,您可以在子组件中使用钩子。每当检测到任何变量发生变化时就会触发它@Input

孩子

import { Component, Input, OnChanges, SimpleChanges } from "@angular/core";

export class ChildComponent implements OnChanges {
  @Input() variable: any;
  @Input() varExample: boolean;

  ngOnChanges(changes: SimpleChanges) {
    if (changes.variable && changes.variable.currentValue) {
      console.log(changes.variable.currentValue);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

工作示例:Stackblitz