Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

angular - Best way to pass styling to a component

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...

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'"/>

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;
}

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...

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

question from:https://stackoverflow.com/questions/35734073/best-way-to-pass-styling-to-a-component

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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" ...>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...