发射和Catch在角分量事件

问题描述 投票:0回答:1

我创建了下面的角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);
  }

}

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

我的想法来解决这个是:

  1. 设置active = true当切换功能发出事件;我想我需要通过面板本身的事件?
  2. 赶上手风琴组件事件。而随着事件通过面板关闭所有其它面板。

这可能吗?怎么样?

angular angular6 angular7
1个回答
2
投票

你能赶上在accordion.component输出事件和subscribe它。

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);
  }

}
© www.soinside.com 2019 - 2024. All rights reserved.