在经历了不同的方法并尝试向angular应用程序的所有页面添加动态CSS之后,我得到了以下解决方案。
要求:根据API和API返回的值生成动态CSS,以更改设计和样式。
解决方案:
代码样例
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完成