moh*_*eli 2 javascript angular
我有这个父组件,它有一个布尔属性,可以由用户通过 UI 中的按钮设置。
我有一组递归子组件,实际上是一棵树,需要响应该布尔属性的更改,即使该布尔属性的值未更改,但用户已按下该按钮。
换句话说,即使该布尔属性是false,并且用户单击该按钮,并且由于某些逻辑,布尔属性根本没有更改并保持为false,我仍然希望通知子组件。
我正在使用ngOnChanges并且正在尝试手动触发事件。
但是在falseto 的情况下false,这意味着没有变化,ngOnChanges则不会调用 on children 组件。
我在这里想念什么?
use*_*994 11
您可以将 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();
}
}
Run Code Online (Sandbox Code Playgroud)
并将其传递给子组件:
<hello [notifier]="subject"></hello>
Run Code Online (Sandbox Code Playgroud)
在您的子组件中,订阅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);
})
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个StackBlitz 示例