javascript - 在 Angular 2 中触发对子组件的更改,即使数据/状态没有更改
问题描述
我有这个父组件,它有一个布尔属性,可以由用户通过 UI 中的按钮设置。
我有一组递归子组件,实际上是一棵树,需要响应该布尔属性的更改,即使该布尔属性的值没有更改,但用户按下了该按钮。
换句话说,即使该布尔属性是false
,并且用户单击该按钮,并且由于某些逻辑,布尔属性根本没有更改并且仍然存在false
,我仍然希望通知子组件。
我正在使用ngOnChanges
并且正在尝试手动触发事件。
但是在 to 的情况下false
,false
这意味着没有变化,ngOnChanges
不会调用 on 子组件。
我在这里想念什么?
解决方案
您可以将 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 示例
推荐阅读
- java - Java 三角递归
- nativescript - Nativescript RadDataForm MultilineText 无法在 Android 上运行
- ios - 在自定义 UIButton 子类上添加带圆角的阴影层
- sql-server - SQL Server 复制粘贴无分栏符
- html - 应用程序缓存 - HTML 5
- python - 从 Python 中的字符列表创建句子(R 代码翻译)
- java - 我们正在做“组”来创造摇滚、纸、剪刀。我们用 1 块石头,2 块纸,3 块剪刀
- perl - AppleScript 替换多个文件中的文本
- node.js - 如何查看实际用于我的应用程序包的软件包列表?
- reactjs - 无法在“历史”上执行“pushState”:函数 addComment() ... 无法克隆