【问题标题】:How do I trigger functions in both the child AND parent component using Event Emitters?如何使用事件发射器触发子组件和父组件中的函数?
【发布时间】:2020-04-06 06:58:32
【问题描述】:

我有一个父子组件,我希望父组件能够在子组件中触发一个功能,同时也允许子组件在父组件中触发一个功能。以下是我为子级触发父级函数所做的工作:

孩子

@Output() callParentFunction = new EventEmitter<any>();
...
this.callParentFunction.emit();

父母

  template: `
    <child-component
      (callParentFunction)="parentfunction($event)"
    >
    </child-component>
  `

这可以触发parentfunction,但我该怎么做呢?我需要使用来自父级的事件发射器来触发子函数。

【问题讨论】:

    标签: angular typescript components eventemitter


    【解决方案1】:

    这样试试

    父母

    template: `
        <child-component
          [events]="eventsSubject.asObservable()"
        >
        </child-component>
      `
    private eventsSubject: Subject<void> = new Subject<void>();
    anyfunction(){  
        this.eventsSubject.next()
     }
    

    孩子

    @Input() events: Observable<void>;
    ngOnInit() {        
      this.events.subscribe(() => 
      //do something
     );   
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用ngOnChanges()。所以你可以处理。

      As Angular docs says:

      默认更改后立即调用的回调方法 如果至少有一个检测器已经检查了数据绑定属性 更改,并且在检查视图和内容子项之前。

      @Component({selector: 'child', template: `...`})
      class ChildComponent implements OnChanges {
        // TODO(issue/24571): remove '!'.
        @Input()
        prop: number;
      
        ngOnChanges(changes: SimpleChanges) {
          // changes.prop contains the old and the new value...
        }
      }
      

      然后从父组件更新一些对象foo,然后ngOnChanges方法将被触发:

      <child-component
        [events]="eventsSubject.asObservable()"
        [prop] = "foo"
      >
      </child-component> 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-06-14
        • 2020-02-22
        • 1970-01-01
        • 1970-01-01
        • 2020-04-16
        • 2019-05-05
        • 2018-10-27
        • 1970-01-01
        相关资源
        最近更新 更多