Angular组件中的Emit和Catch事件

时间:2019-02-05 21:20:39

标签: angular angular6 angular7

我创建了以下Angular 7手风琴组件SlackBlitz Example

export class AccordionComponent {

  @ContentChildren(PanelComponent) panels: QueryList<PanelComponent>;

  ngAfterContentInit() {
    this.panels.forEach((panel) => {panel.active = false;});
  }

  onReset(panel: PanelComponent) {
    this.panels.toArray().forEach(panel => panel.active = false);
  }

} 

PanelComponent如下:

export class PanelComponent {

  @Input() active: boolean;
  @Input() title: string;

  @Output() reset: EventEmitter<PanelComponent> = new EventEmitter();

  toggle() {
    this.active = !this.active;
    if (this.active)
      this.reset.emit(this);
  }

}

打开面板时,我需要关闭所有其他面板...

我解决这个问题的想法是:

    设置active = true时,在切换功能中发出
  1. Emit事件; 我想我需要在活动中通过小组吗?

  2. 在“手风琴”组件中捕获该事件。 并在事件通过面板后,关闭所有其他面板。

这可能吗?怎么样?

1 个答案:

答案 0 :(得分:2)

您可以在自己的accordion.componentsubscribe中捕获输出事件。

PanelComponent

import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'panel',
  templateUrl: './panel.component.html'
})

export class PanelComponent {

  @Input() active: boolean;
  @Input() title: string;

  @Output() activate = new EventEmitter();

  toggle() {
    this.active = !this.active;
    if (this.active) {
      this.activate.emit();
    }   
  }

}

AccordionComponent

import { Component, ContentChildren, QueryList } from '@angular/core';

import { Subject } from 'rxjs'
import { takeUntil } from 'rxjs/operators'

import { PanelComponent } from './panel.component';

@Component({
  selector: 'accordion',
  templateUrl: './accordion.component.html'
})

export class AccordionComponent {

  @ContentChildren(PanelComponent) panels: QueryList<PanelComponent>;

  destroy$ = new Subject<boolean>();

  ngAfterContentInit() {

    this.panels.forEach((panel) => {
      panel.active = false;
      panel.activate.pipe(
        takeUntil(this.destroy$)
      ).subscribe(() => {
        this.closeAllButPanel(panel);
      })
    });

  }

  ngOnDestroy() {
    this.destroy$.next(true);
    this.destroy$.unsubscribe();
  }

  closeAllButPanel(panelToIgnore: PanelComponent) {
    this.panels.filter(p => p!==panelToIgnore).forEach(panel => panel.active = false);
  }

}