首页 > 解决方案 > 从Angular中的兄弟组件调用方法和属性?

问题描述

我是 Angular 的新手。我有两个组件,当组件 A 单击时,组件 2 应该显示(添加一个类)。如果它是父子组件,我可以通过调用模板引用变量来完成。但在这种情况下,它不是。他们是兄弟姐妹。我尝试了很多地方,但它们只显示通信数据。最好的方法是什么?

比较-A HTML

<app-comp-a>
<button (click)="profilePanel.panelOpen()"></button>
<app-comp-a>

比较-B HTML

<app-comp-b #profilePanel>
<div *ngClass="panelCss">
<p>panel opened</p>
</div>
<app-comp-b>

比较-B TS

panelCss = 'hidePanel';

panelOpen(){
panelCSS = 'showPanel';
}

标签: angular

解决方案


您所需要的只是一个服务,其中您有一个类型的变量Subject。使用此变量,您将能够在组件 B 中等待组件 A 发送内容。

服务.ts

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable()
export class SiblingServiceService {

  showSibling = new Subject<boolean>();

  constructor() { }

}

showSibling是您的主题,您可以在其中等待组件 B 中的数据

A组份

import { theService } from 'path/to/service'

...

export class SiblingAComponent implements OnInit {

  constructor(private service: theService) { }

  ngOnInit() {
  }

  openPanel(){
    this.service.showSibling.next(true);
  }
}

B组份

import { theService } from 'path/to/service'

...

export class SiblingBComponent implements OnInit {

  active: boolean = false;

  constructor(private service: theService) { }

  ngOnInit() {
  }

  openPanel(){
    this.service.showSibling.subscribe(res => {
      this.active = res
    });
  }
}

这是一个stackblitz工作示例


推荐阅读