我的项目结构如下:
app
-----pages-parts |
|header
|footer
-----pages |
|homepage
|contacts
|...etc...
-----airports |
|airport-template
|airport-1
|airport-2
|...etc...
在我的应用程序组件中.html我有:
<app-header></app-header>
<router-outlet></router-outlet> //<- here I load homepage for first instance
<app-footer></app-footer>
因此,我在所有页面中加载标题组件。
然后,例如,在机场部分,我加载机场模板组件,并使用@Input将存储在机场-1组件中的内容(文本和其他内容(放入
。同样,我需要根据机场-1、机场-2 导航更改header
背景,但我仍然无法弄清楚。
我再次尝试@Input
但没有成功。 我还尝试在airport-1.component.scss中的同一标头类上应用不同的样式,但没有成功(我认为这是由于视图封装(。
有没有办法解决我的问题?
任何建议将不胜感激。
在 ngOnInit 方法的标头组件中,您必须订阅每个路由的更改。
import { NavigationEnd, Router, ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs';
…
subscriptionRoute: Subscription;
classBackground: string = '';
…
constructor(
private router: Router
) {}
ngOnInit() {
this.subscriptionRoute = this.router.events.subscribe((event) => {
if (event instanceof NavigationEnd) {
console.log(event.url);
//here set classBackground property
}
});
}
在标头 html 中使用 ngClass 分配类背景
问候
有一些方法可以做到这一点: 1:将样式放置在父项内部,并在子选择器前面加上/ng-deep/
这样样式就不会"封装"到父项中,并且会影响子项。 2:订阅router.events.subscribe(event => analyze(router.url))
并处理路由器的URL 3:我最喜欢的女巫会将逻辑保留在父组件中,但样式保留在header.scss中
<app-header [ngClass]="{'blue-background': shouldBeBlue}"/>
<!-- header.scss -->
:host.blue-background {
.some-element {
background: blue;
}
}