EEAH
EEAH

Reputation: 747

Angular class not applied when using javascript literal

When a class is added in the template literal it is not changing the style of the element:

comp.html

<div data-js = "tutorial" class ="center main">
    
</div>

comp.scss

.testt {
    color: red;
}

comp.ts

public tutorial: Element;
constructor() { }

ngOnInit() {

    this.tutorial = document.querySelector("[data-js='tutorial']");
    this.tutorial.innerHTML = `
        <h1 class = "testt">
            Welcome
        </h1>
    `;
}

<h1> is not colored red

Upvotes: 1

Views: 833

Answers (2)

Muhammed Albarmavi
Muhammed Albarmavi

Reputation: 24414

by default component emulate native scoping of styles by adding an attribute containing surrogate id to the Host Element and pre-processing the style rules provided via styles or styleUrls, and adding the new Host Element attribute to all selectors.

enter image description here

so you can set component encapsulation to none

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  encapsulation:ViewEncapsulation.None
})

or add the class in the global style file so the class will effect any element in your project have that class

style.scss

.testt {
    color: red;
}

Upvotes: 2

Adrian Brand
Adrian Brand

Reputation: 21638

The injected html is not part of the component so the components CSS does not affect it. use

::ng-deep .testt {
    color: red;
}

or add the css to a global style sheet

Upvotes: 3

Related Questions