angular - 从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';
}
解决方案
您所需要的只是一个服务,其中您有一个类型的变量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
});
}
}
推荐阅读
- c# - 如何在AngularJS中将十进制解析为固定的2位数字
- c - 使用循环从数组中的元素中查找累积和?
- php - 无法在 dialogflow(api.ai) 中解析 webhook json 响应
- android - FireStorePagingAdapter 未接收实时更新
- python - 按顺序固定列
- php - preg_match 与多个查找
- ruby-on-rails - Rails ActiveQuery 接口
- web-services - 在 ColdFusion 中创建服务
- javascript - 如何在角度 4 中设置授权标头(不在 Access-Control-Request-Headers 内)。它应该是授权:值
- r - 有条件地替换数组中的值