Javascript 根据变量angular生成动态css
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46047502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generate dynamic css based on variables angular
提问by Vikram
I am working on a admin panel developed with angular 4 and trying to integrate a sections to customize styling like change color, bg etc. I already have developed a sections to save settings in database got them on app load as json using API.
我正在使用 angular 4 开发一个管理面板,并尝试集成一个部分来自定义样式,如更改颜色、bg 等。我已经开发了一个部分来保存数据库中的设置,使用 API 将它们作为 json 加载到应用程序中。
Now I am trying to generate a dynamic css using values from json, I tried with following code in main component but its not working
现在我正在尝试使用来自 json 的值生成动态 css,我尝试在主要组件中使用以下代码但它不起作用
@Component({
templateUrl: 'card.html',
styles: [`
.card {
height: 70px;
width: 100px;
color: {{css.cardColor}};
}
`],
})
I am not sure how I should load the css values in component and use them in style tag. I didnt find any other solution for same.
我不确定应该如何在组件中加载 css 值并在样式标签中使用它们。我没有找到任何其他解决方案。
Another way is to use angular animation concept but the css is going to be huge and its not possible to implements it whole with angular animation using triggers and all. I believe there is a solution for this as it seems a genuine requirements and should have done by lots of other developers.
另一种方法是使用角度动画概念,但 css 将是巨大的,并且不可能使用触发器和所有的角度动画来实现它。我相信有一个解决方案,因为它似乎是一个真正的要求,应该由许多其他开发人员完成。
Any help is appreciable.
任何帮助都是可观的。
Edit : can not use ngStyle as its going to be applied on almost all elements as its for whole application and not only for specific element.
编辑:不能使用 ngStyle 作为其将应用于几乎所有元素作为整个应用程序,而不仅仅是特定元素。
采纳答案by Vikram
After going through different methods and approached to add dynamic css to all pages on angular app I ended up with following solutions.
在经历了不同的方法并尝试向 angular 应用程序上的所有页面添加动态 css 之后,我最终得到了以下解决方案。
Requirement : generate dynamic css based on values returned from and API to change design and styling.
要求:根据返回的值和 API 生成动态 css 以更改设计和样式。
Solution :
解决方案 :
- create a new component and create a service to load dynamic css variables from API.
- Add style tag in template file and use variable values for properties.
- Load this template on all pages or on main template.
- On app build style will be moved to head tag.
- 创建一个新组件并创建一个服务来从 API 加载动态 css 变量。
- 在模板文件中添加样式标签并为属性使用变量值。
- 在所有页面或主模板上加载此模板。
- 在应用程序构建样式将移动到 head 标签。
Code sample
代码示例
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 */
}
}
Now apply css using jquery or javascript to append css with help of function like following
现在使用 jquery 或 javascript 应用 css 以在如下函数的帮助下附加 css
appendCss(customData)
{
let text = '.custom-form-1 {
background-image: url("`+customData.background_image+`");
}';
$(document).ready(function(){
$("style").append(text);
});
}
and call this function after loading custom data from service or other variable like I did it ngOnInit
并像我一样从服务或其他变量加载自定义数据后调用此函数 ngOnInit
ngOnInit(){
this.appendCss(this.customizeFormData);
}
Its using jquery but can be done with javascript/typescript as well if you dont want to use jquery in your angular app
它使用 jquery,但如果您不想在 angular 应用程序中使用 jquery,也可以使用 javascript/typescript 完成
Other useful resource https://github.com/angular/angular/issues/9343#issuecomment-312035896
其他有用的资源 https://github.com/angular/angular/issues/9343#issuecomment-312035896
回答by Ajinkya Dhote
you can use ngStyle to dyanaically add the css to your page from json.
您可以使用 ngStyle 从 json 动态地将 css 添加到您的页面。
<div [ngStyle]="{'color': variable ? 'red' : 'blue'}"></div>
An another example of same can be
另一个相同的例子可以是
<div md-card-avatar [ngStyle]="{'background-image': 'url(' + post.avatar + ')', 'background-size': 'cover' }"></div>
here i have loaded background image from the json
在这里,我从 json 加载了背景图像
回答by Eliseo
You can bind only style.color:
您只能绑定style.color:
<div class="card" [style.color]="cardColor">lorem ipsum</div>
回答by Rohan Fating
ngClassis used to set the dynamic class basis of your variable value as below
ngClass用于设置变量值的动态类基础,如下所示
Ts File Component:
Ts 文件组件:
@Component ({
selector:'simple-comp',
template:` <ol class="breadcrumb">
<li *ngClass="{'active': step==='step1'}" (click)="step='step1; '">Step1</li>
<li *ngClass="{'active': step==='step2'}" (click)="step='step2'">Step2</li>
<li *ngClass="{'active': step==='step3'}" (click)="step='step3'">Step3</li>
</ol>`
})
export class SimpleComponent {
public step: string = 'step1'; // change value like step1, step2, step3
}
HTML Code:
HTML代码:
<some-element [ngClass]="{'first': true, 'second': true, 'third': false}">
...
</some-element>
回答by Matt Saunders
I wanted to dynamically style an element nested within a component, (specifically http://tb.github.io/ng2-nouislider/), so similar to the OP, ngStyle was not suitable.
我想动态设置嵌套在组件中的元素的样式(特别是http://tb.github.io/ng2-nouislider/),因此与 OP 类似,ngStyle 不适合。
My approach was to use a reference variable in my template (https://angular.io/api/core/ViewChild) to access the native element of the component and find the target child node using querySelector (https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector).
我的方法是在我的模板 ( https://angular.io/api/core/ViewChild) 中使用一个引用变量来访问组件的本机元素并使用 querySelector ( https://developer.mozilla .org/en-US/docs/Web/API/Document/querySelector)。
The required style was then applied with Renderer 2. Example below and on https://stackblitz.com/edit/angular-r3bs1d.
然后使用渲染器 2 应用所需的样式。 下面和https://stackblitz.com/edit/angular-r3bs1d上的示例。
import { Component, Renderer2, ViewChild, AfterViewInit } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {
backgroundColour = '#ff0000';
constructor(private renderer: Renderer2) { }
@ViewChild('parent', { static: false }) parent;
ngAfterViewInit(){
this.renderer.setStyle(this.parent.nativeElement.querySelector('.child'), 'background', this.backgroundColour);
}
}
HTML:
HTML:
<div #parent>
<div class="child">Child Element</div>
</div>
For minor styling changes at least, I think this is a feasible solution.
至少对于较小的样式更改,我认为这是一个可行的解决方案。
回答by Simon_Weaver
I'm not saying it's applicable but the angular/flex-layoutlibrary does a lot of manipulation of styles.Looking at the source-code may help give you some ideas.
我并不是说它适用,但该angular/flex-layout库对样式进行了大量操作。查看源代码可能会帮助您提供一些想法。
Remember to take advantage of directives, services/dependency injection.
记住要利用指令、服务/依赖注入。
For example here's a few useful classes in the flex-layout library that may be relevant:
例如,这里有一些可能相关的 flex-layout 库中的有用类:
StyleUtils, StyleDirective, MatchMedia(dynamically create stylesheet tag)
StyleUtils, StyleDirective, MatchMedia(动态创建样式表标签)

