首页 > 解决方案 > 在 Angular 2 中触发对子组件的更改,即使数据/状态没有更改

问题描述

我有这个父组件,它有一个布尔属性,可以由用户通过 UI 中的按钮设置。

我有一组递归子组件,实际上是一棵树,需要响应该布尔属性的更改,即使该布尔属性的值没有更改,但用户按下了该按钮

换句话说,即使该布尔属性是false,并且用户单击该按钮,并且由于某些逻辑,布尔属性根本没有更改并且仍然存在false,我仍然希望通知子组件。

我正在使用ngOnChanges并且正在尝试手动触发事件

但是在 to 的情况下falsefalse这意味着没有变化,ngOnChanges不会调用 on 子组件。

我在这里想念什么?

标签: javascriptangular

解决方案


您可以将 aSubject作为输入传递给子组件。

在您的父组件中,创建一个主题,如下所示:

import { Component } from '@angular/core';
import { Subject } from 'rxjs';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  subject = new Subject<string>();

  handleClick() {
    // This will send a message via the subject
    this.subject.next("TEST");
  }

  // Complete the subject when your component is destroyed to avoid memory leaks
  ngOnDestroy() {
    this.subject.complete();
  }
}

并将其传递给子组件:

<hello [notifier]="subject"></hello>

在您的子组件中,订阅Subject,并在订阅回调中执行您需要执行的任何操作:

import { Component, Input } from '@angular/core';
import { Subject } from 'rxjs';

@Component({
  selector: 'hello',
  template: `<h1>Hello {{name}}!</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {
  @Input() notifier: Subject<any>;

  ngOnInit() {
    if (this.notifier != null) {
      this.notifier.subscribe((event) => {
        // This will be logged every time the subject.next is called.
        console.log("HelloComponent heard", event);
      })
    }
  }
}

这是一个StackBlitz 示例


推荐阅读