我的项目结构如下:
app
-----pages-parts |
|header
|footer
-----pages |
|homepage
|contacts
|...etc...
-----airports |
|airport-template
|airport-1
|airport-2
|...etc...
在我的app.component.html中,我拥有:
<app-header></app-header>
<router-outlet></router-outlet> //<- here I load homepage for first instance
<app-footer></app-footer>
因此,我在所有页面中加载标头组件。
然后,例如,在“机场”部分中,我加载了airport-template组件,并使用@Input放置了存储在airport-1组件中的内容(文本和其他内容)。
以同样的方式,我需要根据Airport-1,airport-2导航来更改header
背景,但仍然无法弄清。
我再次尝试@Input
,但没有成功。
我还尝试将不同的样式应用于airport-1.component.scss中的同一标头类,但没有成功(我认为这是由于View Encapsulation所致)。
有没有办法解决我的问题?
任何建议将不胜感激。
答案 0 :(得分:1)
在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分配classBackground
致谢
答案 1 :(得分:0)
有一些方法可以做到这一点:
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;
}
}