angular - 使用模块中的变量在装饰器中添加自定义 CSS
问题描述
我有一个 NativeScript Angular 应用程序,我想为平板电脑使用单独的 CSS。因此,如果相关,我正在检查deviceType
并tns-core-modules/platform
在装饰器中添加平板电脑 CSS,如下所示:
import { Component, OnInit } from '@angular/core';
import { DeviceType } from 'tns-core-modules/ui/enums';
import { device } from 'tns-core-modules/platform/platform';
@Component({
moduleId: module.id,
templateUrl: './login.component.html',
styleUrls: [
'./login.component.css',
device.deviceType === DeviceType.Tablet ? './login.component.tablet.css' : ''
]
})
export class LoginComponent implements OnInit {
}
当我运行常规时,这工作正常tns run <platform>
,但是当我想创建一个包(并且使用 webpack)时,我得到一个错误:
装饰器中只能引用初始化的变量和常量,因为“设备”中的模板编译器需要此变量的值
我认为我原则上理解它在抱怨什么,但我希望device
在我的组件被实例化时已经初始化,因为设备来自tns-core-modules
模块。
谁能想到一种允许这种使用的方法?我看过这个博客,其中 Eddy 做了类似的事情ngOnInit
,但在 .
谢谢!
解决方案
It surprises me a little that it isn't working in ngOnInit
since your view hasn't yet been constructed. You could push it even sooner by using the constructor
, but you might run into the same problem.
作为最后的手段,您也可以只制作一个单独的组件,然后选择哪个组件包含在您的模板中,并带有ngIf
.
不过,可能值得调查一下为什么您的 Eddy 示例的实现不起作用。