将样式传递给组件的最佳方法

将样式传递给组件的最佳方法

本文介绍了将样式传递给组件的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个叫做InputEdit的组件(基本上是一个Label,当您单击它时就可以对其进行编辑...足够简单)并且此组件具有其自身的阴影DOM CSS样式.但是,当然,每个托管组件都希望为输入组件设置自己的字体大小和颜色...

So I have this component called InputEdit (basically a Label that can be edited when you click on it... simple enough)and this component has its own shadowed DOM CSS styling.But of course each hosting component will want to set its own font size and color for the input component...

那么最好的方法是什么?您可以只传入样式类,然后将整个CSS应用于组件吗?还是像下面这样手动传递每个值会更好:

So what would be the best way? Can you just pass in a styling class and apply the entire CSS to the component? Or would it be better to pass each value manually as in:

     <InputEdit [color]="'red'"/>

这似乎需要做很多工作,但是由于我们正在使用影子或模拟DOM,因此我们不能仅仅从外部控制CSS.

Which would seem a lot of work, but again since we are using the shadow or emulated DOM, we can't just control the CSS externally.

我也知道您可以通过以下方式拼接阴影并定位直接元素:

I am also aware that you can splice open the shadow and target direct elements via:

/* styles.css */
UserInfo /deep/ InputEdit label {
    color: red;
    font-size: 1.1em;
}

基本上,这将允许您输入名为UserInfo/deep(任何级别)/自定义组件InputEdit的自定义组件,并使用红色标记目标标签...

Which will basically allow you to enter into a custom component named UserInfo / deep (any level ) / custom component InputEdit and target label with color red...

但是再次,我想知道专门针对ng2的最佳方法是什么,例如将类配置传递到指令中?

But again, I am wondering what is the best approach specifically for ng2 like passing a class config into a directive maybe?

推荐答案

我只是在InputEdit上使用styles输入属性,然后传入具有所需样式的对象:

I would just use a styles input property on InputEdit, and pass in an object with the desired styles:

<InputEdit [styles]="stylesObj">                 // in host component's template

stylesObj = {font-size: '1.1em', color: 'red'};  // in host component class

<input [ngStyle]="stylesObj" ...>                // in InputEdit component's template

如果您要设置多个DOM元素,请传入一个更复杂的对象:

If you have multiple DOM elements you want to style, pass in a more complex object:

<InputEdit [styles]="stylesObj">

stylesObj = {
  input: {font-size: '1.1em', color: 'red'}
  label: { ... }
};

<label [ngStyle]="styles.label" ...>
<input [ngStyle]="styles.input" ...>

这篇关于将样式传递给组件的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 11:18