Vik*_*ram 20 javascript css typescript angular2-template angular
我正在开发一个用angular 4开发的管理面板,并试图集成一个部分来自定义样式,如更改颜色,bg等.我已经开发了一个部分来保存数据库中的设置,使用API将它们作为json加载到json.
现在我尝试使用json中的值生成动态css,我尝试使用主要组件中的以下代码,但它无法正常工作
@Component({
templateUrl: 'card.html',
styles: [`
.card {
height: 70px;
width: 100px;
color: {{css.cardColor}};
}
`],
})
Run Code Online (Sandbox Code Playgroud)
我不确定如何在组件中加载css值并在样式标记中使用它们.我没有找到任何其他解决方案.
另一种方法是使用角度动画概念,但css将是巨大的,并且不可能使用触发器和所有的角度动画来实现它.我相信有一个解决方案,因为它似乎是一个真正的要求,应该由许多其他开发人员完成.
任何帮助都很明显.
编辑:不能使用ngStyle作为几乎所有元素应用于整个应用程序,而不仅仅是特定元素.
Aji*_*ote 17
你可以使用ngStyle从json中动态地将css添加到你的页面.
<div [ngStyle]="{'color': variable ? 'red' : 'blue'}"></div>
Run Code Online (Sandbox Code Playgroud)
另一个例子可以是
<div md-card-avatar [ngStyle]="{'background-image': 'url(' + post.avatar + ')', 'background-size': 'cover' }"></div>
Run Code Online (Sandbox Code Playgroud)
在这里我加载了json的背景图片
Vik*_*ram 16
在经历了不同的方法并接近将动态css添加到角度应用程序的所有页面后,我最终得到了以下解决方案.
要求:根据返回的值和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 */
}
}
Run Code Online (Sandbox Code Playgroud)
现在使用jquery或javascript应用css来附加css以及如下函数的帮助
appendCss(customData)
{
let text = '.custom-form-1 {
background-image: url("`+customData.background_image+`");
}';
$(document).ready(function(){
$("style").append(text);
});
}
Run Code Online (Sandbox Code Playgroud)
从服务或其他变量加载自定义数据后调用此函数,就像我做的那样 ngOnInit
ngOnInit(){
this.appendCss(this.customizeFormData);
}
Run Code Online (Sandbox Code Playgroud)
它使用jquery,但也可以用javascript/typescript完成,如果你不想在你的角度应用程序中使用jquery
其他有用的资源 https://github.com/angular/angular/issues/9343#issuecomment-312035896
ngClass 用于设置变量值的动态类基础,如下所示
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
}
Run Code Online (Sandbox Code Playgroud)
HTML代码:
<some-element [ngClass]="{'first': true, 'second': true, 'third': false}">
...
</some-element>
Run Code Online (Sandbox Code Playgroud)
你只能绑定"style.color"
<div class="card" [style.color]=cardColor>lorem ipsum</div>
Run Code Online (Sandbox Code Playgroud)