Angular2 CSS样式/类字符串作为组件的输入 [英] Angular2 CSS style/class strings as inputs to component
问题描述
我有一个包装两个span
元素的组件.我希望父组件能够通过将CSS类和样式指定为输入(最好是简单的字符串)来对内部的两个span
进行样式设置.这是我想要的样子的简化示例:
I have a component that wraps two span
elements. I would like parent components to be able to style the inner two span
s by specifying CSS classes and styles as inputs (preferably as simple strings). Here's a simplified example of what I would like this to look like:
@Component({
selector: 'my-app',
template: `
<div>
<app-two-spans [classArg1]="'class1'" [classArg2]="'class2'"
[styleArg1]="'width: 100px'" [styleArg2]="'width:200px'"></app-two-spans>
</div>
`, style: `
::ng-deep .class1 {
border: 1px solid black;
}
::ng-deep .class2 {
border: 1px solid blue;
}
`
})
export class App {
}
两个跨度分量(子级)
import {Component, Input, Output, EventEmitter} from '@angular/core';
@Component({
selector: 'app-two-spans',
template: `
<span *ngIf="flag" [ngClass]="classArg1" [ngStyle]="styleArg1"
(click)="flag = !flag">click me</span>
<span *ngIf="!flag" [ngClass]="classArg2" [ngStyle]="styleArg2"
(blur)="flag = !flag" contenteditable="true">
click me to change my value</span>
`
})
export class TwoSpansComponent {
flag: boolean = true;
@Input() styleArg1: string;
@Input() styleArg2: string;
@Input() classArg1: string;
@Input() classArg2: string;
constructor() {}
}
问题
类样式似乎可以在我的本地环境中使用(尽管由于某些原因它似乎不适用于Plunker).但是,style
没有出现.我看过其他有关样式作为输入的文章,但是从我所见,这通常是通过传递样式-值对(
Problem
The class styling seems to work in my local environment (though it doesn't seem to work on Plunker for some reason). However, the style
s are not showing up. I've seen other posts about styles as inputs, but from what I've seen this is usually done by passing style-value pairs (see accepted answer here). However, I would really like to pass these styles as a simple string to make working with the component easier.
I notice the following error in the console: ERROR Error: Cannot find a differ supporting object 'width: 100px'
. I'm not sure what this means at all.
有没有办法做到这一点?我该如何赋予父级组件样式化子级的能力?
Is there a way to do this? How can I give parent components the ability to stylize children?
推荐答案
ngStyle
接受Object
而不是纯字符串.您可以通过以下方式传递样式:
ngStyle
accepts an Object
instead of plain string. You can pass your styles as:
[styleArg1]="{ width: '100px' }"
[styleArg2]="{ width: '200px' }"
这篇关于Angular2 CSS样式/类字符串作为组件的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!