5

I'm appending a childitem div to another div inside the same angular component. Then I assign a class to it. (using class list) It succesfully inserts the element and also adds the class to it but non of my css class properties are applied to it.

If I add the element manually inside my html code (including the class attribute) the element is shown correctly.

Why is this happening?

Typescript code:

let parent = document.getElementById('playingfield');
        let cactus = document.createElement('div');
        cactus.classList.add('cactus');
        parent.appendChild(cactus);

HTML code of manually inserting the div:

<div class="cactus"></div>
3
  • 2
    Possible duplicate of Can't change CSS style in AngularJS Commented Jan 10, 2019 at 11:30
  • sorry wrong tag. I need a solution for normal "Angular" not angularjs. It doesn't find the angular.something keyword. Or why doesn't it find the angular.somthing methods? Commented Jan 10, 2019 at 11:59
  • Why are you adding a div element in typescript and not using *ngIf in your html template? This looks like bad code style to me. Commented Jan 10, 2019 at 12:14

1 Answer 1

14

To apply the runtime css into your html you need to use :host feature of angular.

In your .css or .scss file set css by this way.

:host ::ng-deep .cactus{
    // Your css hear
}
Sign up to request clarification or add additional context in comments.

2 Comments

Works perfectly, thanks! For those interested in what this feature does, see: blog.angular-university.io/angular-host-context
Thanks! I was looking everywhere and couldn't find an answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.