angular中可用的直接方法是使用ngstyle,如下所示
<div [ngStyle]="{'color': style.colorVal ? style.colorVal : '#000', 'font-size' : style.fontSize ? style.fontSize : '16px' }"></div>
在经历了不同的方法并try 将动态css添加到angular应用程序的所有页面之后,我最终得到了以下解决方案.
要求:根据API返回的值生成动态css,以更改设计和样式.
解决方案:
- 创建一个新组件并创建一个服务来从API加载动态css变量.
- 在模板文件中添加样式标记,并对特性使用变量值.
- 在所有页面或主模板上加载此模板.
- 应用程序上的构建样式将移动到head tag.
代码示例
import { CssService} from './Css.service';
@Component({
selector: 'DynamicCss',
templateUrl: './DynamicCss.component.html',
styleUrls: ['./DynamicCss.component.scss']
})
export class ServiceProviderComponent implements OnInit {
cssVariables: any;
constructor(private cssService:CssService){
/* call the service/api to get the css variable values in cssVariables */
}
}
现在,使用jquery或javascript应用css,借助下面的函数附加css
appendCss(customData)
{
let text = '.custom-form-1 {
background-image: url("`+customData.background_image+`");
}';
$(document).ready(function(){
$("style").append(text);
});
}
并在从服务或其他变量加载自定义数据后调用此函数,就像我ngOnInit
年前那样
ngOnInit(){
this.appendCss(this.customizeFormData);
}
它使用jquery,但如果你不想在应用程序中使用jquery,也可以使用javascript/typescript
其他有用资源https://github.com/angular/angular/issues/9343#issuecomment-312035896