![](/img/trans.png)
[英]Angular2 navigate from a component to a sibling component without tearing down the first
[英]How to style a sibling component in Angular2?
我有一个包含徽标,搜索栏和routeroutlet的搜索组件。 搜索的执行导航到结果列表,这是此处概述的伪html:
<search>
<logo></logo>
<searchbar></searchbar>
<result-list></result-list>
</search>
我希望在结果页面上设置徽标和搜索栏的样式不同,因此我尝试使用:host >>> logo
和/deep/
替代方法从result-list
组件中选择徽标。 那不行 有没有办法选择兄弟姐妹?
这里有一个小的plnkr来演示问题。 http://plnkr.co/edit/Q0CLjcsftbqe0kHKrKks?p=preview在这里,我想从风格resultlist
的logo
和searchbar
为黑色。
与Jens Habegger的解决方案类似的解决方案,它使用:host-context(myCssClass)
和一个有条件的解决方案。 样式需要添加到logo
和搜索searchbar
组件中。
<search>
<logo [class.myCssClass]="isSearchResultList"></logo>
<searchbar [class.myCssClass]="isSearchResultList"></searchbar>
<result-list></result-list>
</search>
:host-context(.myCssClass) {
color: black;
}
您尝试的基本上是在多个组件之间共享全局应用程序状态isSearchResultList: boolean
。
显而易见的幼稚解决方案是将状态保留在相应的共享父组件上,然后根据当前路由器出口对其进行设置。
<search>
<logo [isSearchResultList]="isSearchResultList"></logo>
<searchbar [isSearchResultList]="isSearchResultList"></searchbar>
<result-list></result-list>
</search>
您可以将服务用于组件之间的通信,而可以使用ngClass进行动态样式化。
notification.service.ts
import {Injectable, EventEmitter} from '@angular/core';
@Injectable()
export class NotificationService {
private static _emitters: { [ID: string]: EventEmitter<any> } = {};
static get(ID: string): EventEmitter<any> {
if (!this._emitters[ID]) {
this._emitters[ID] = new EventEmitter();
}
return this._emitters[ID];
}
}
当同级组件运行时,发送一条消息。
bar.component.ts
import { NotificationService } from 'notification.service';
....
ngOnInit() {
NotificationService.get('barcomponent').emit(true);
}
ngOnDestroy() {
NotificationService.get('barcomponent').emit(false);
}
...
听取来自组件的传入消息。
foo.component.ts
import { NotificationService } from 'notification.service';
....
ngOnInit() {
NotificationService.get('barcomponent').subscribe(value => {
this.activateStyle = value;
});
}
....
您可以通过ngClass应用任何类
foo.component.html
....
<div [ngClass]="{'my-css-class':activateStyle}">
...
</div>
....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.