代码之家  ›  专栏  ›  技术社区  ›  mohammad rostami siahgeli

触发对角度2中的子组件的更改,即使数据/状态没有更改

  •  1
  • mohammad rostami siahgeli  · 技术社区  · 8 年前

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

    我有一个递归的子组件集,实际上是一个树,它需要响应布尔属性的更改, 即使布尔属性的值没有改变,但是用户已经按下了那个按钮 .

    false ,然后用户单击该按钮,由于某些逻辑,布尔属性根本不会更改并保持不变

    我在用 ngOnChanges trying to trigger the event manually .

    ,也就是说没有变化 恩贡切格斯 不调用子组件上的。

    我错过了什么?

    1 回复  |  直到 8 年前
        1
  •  7
  •   user184994    8 年前

    你可以通过 Subject

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

    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>
    

    主题

    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 example