我对角质很陌生。我有两个组件,当组件A单击时,组件2应该显示(添加一个类)。如果它是父子组件,我可以通过调用模板引用变量来完成它。但在这种情况下,事实并非如此。他们是兄弟姐妹。我试过很多地方,但它们只显示通信数据。做这件事的最佳方法是什么?
Comp-一个HTML
<app-comp-a>
<button (click)="profilePanel.panelOpen()"></button>
<app-comp-a>Comp-B HTML
<app-comp-b #profilePanel>
<div *ngClass="panelCss">
<p>panel opened</p>
</div>
<app-comp-b>Comp-B TS
panelCss = 'hidePanel';
panelOpen(){
panelCSS = 'showPanel';
}发布于 2020-07-09 09:41:12
您所需要的只是一个服务,其中有一个类型为Subject的变量。有了这个变量,您将能够在组件B中等待组件A发送某些内容。
service.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
});
}
}https://stackoverflow.com/questions/62811357
复制相似问题