我试图根据URL参数在组件中加载css样式。基本上,用户将像SOME_URL/{screenSize}/{type}一样加载页面。这将始终加载相同的组件,但使用不同的CSS样式。我已经在使用路由器并设置了参数--如何动态加载CSS文件?有可能吗?
下面是一些代码--基本上目标不是加载示例中定义的静态CSS文件,而是加载类似于screen.component.21-5.a.css的内容。
@Component({
selector: 'app-screen',
templateUrl: './screen.component.html',
styleUrls: ['./screen.component.css']
})
export class ScreenComponent implements OnInit {
public screenType = 'a';
public screenSize = '21-5';
ngOnInit() {}
constructor(private mediaService: MediaService, private route: ActivatedRoute) {
this.parameterSubscription = route.params.subscribe((params) => {
if (params.size) {
this.screenSize = params.size;
}
if (params.type) {
this.screenType = params.type;
}
});
}
...
}发布于 2018-01-15 09:09:30
您不能这样做,因为角要求样式声明是静态可分析的。这是为AOT编译所做的。在运行JavaScript时,所有的模板和样式都会被编译到ng build --prod中,并且样式是提前导入的。因此,如果您可以使用一些条件来重新加载样式,那么该代码将不再是静态可分析的(只有在运行时才能知道screenSize变量,那么我们在提前构建时应该导入哪种样式?),从而导致无法编译AOT。(不,无法编译这两种样式,然后在运行时导入它们-这意味着我们可以理解函数将产生什么样的输出,这几乎是不可能的--参见停止问题)
但是您可以(而且应该)根据屏幕大小使用ngClass在css类之间切换。
发布于 2018-01-15 09:06:40
您可以使用ngClass
在html中
<div class="gradient " [ngClass]="{'class-21-5': screenSize ==='21-5', 'class-a': screenType==='a'}">
...
</div>您可以将不同的类放入不同的文件中,并在需要时将其导入到组件上。
@Component({
selector: 'app-screen',
templateUrl: './screen.component.html',
styleUrls: ['./screen.component.css', './my-other-style.css']
})https://stackoverflow.com/questions/48259717
复制相似问题