Changing style class attributes dynamically in Ang

2019-08-31 05:40发布

问题:

I have the following code in Angular 6:

<div [innerHtml]="content"></div>

I get the content variable from a service call (i.e. an external library). It contains class names, such as p1:

var content = '<p class="p1">This is some text</p>';

Now, I'm migrating this code from AngularJS. In AngularJS, I used to manipulate css classes like p1 in the directive template:

.p1 {
   font-family: {{theFamily}};
}

But when I try to do the same in the Angular 6 component style sheet, I get Module build failed: Syntax Error.

Any ideas how to obtain the same result?

UPDATE Please see this StackBlitz, it does not work because it doesn't accept {{ }} in the css. This worked in AngularJS.

回答1:

You can't use angular binding in Component scss. It should be used only in templates. You can use [ngStyle] which will call component function and return css properties as object.

Template:

<div [ngStyle]="getStyles()">This is test</div>

getStyles(){
    let styles = {
    'background-color': this.isExpired ? 'red' : 'transparent',
    'font-weight': this.isImportant ? 'bold' : 'normal'
  };
  return styles;
}


标签: angular