angular 中可用的直接方法是使用 ngstyle,如下所示
<div [ngStyle]="{'color': style.colorVal ? style.colorVal : '#000', 'font-size' : style.fontSize ? style.fontSize : '16px' }"></div>
在经历了不同的方法并尝试将动态 css 添加到 angular 应用程序的所有页面后,我最终得到了以下解决方案。
要求:根据返回的值和 API 生成动态 css 以更改设计和样式。
解决方案 :
- 创建一个新组件并创建一个服务来从 API 加载动态 css 变量。
- 在模板文件中添加样式标签并为属性使用变量值。
- 在所有页面或主模板上加载此模板。
- 在应用程序构建样式将移动到 head 标签。
代码示例
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,但如果您不想在 Angular 应用程序中使用 jquery,也可以使用 javascript/typescript 完成
其他有用的资源 https://github.com/angular/angular/issues/9343#issuecomment-312035896