0

I am trying to add a new element to a preexisting HTML element with Javascript however the class that I add has no effect. This function is called in ngOnInit()

renderHand ( cards:Array<string> )
{

  var hand:HTMLElement = document.getElementById ( "hand-list-1" );

  for ( var card of cards )
  {
    // Create card
    var imgElement = document.createElement ( "img" );
    // here
    imgElement.src = `assets/cards/${card}.png`;
    imgElement.classlist.add ( "card-img-style" );

    var liElement = document.createElement ( "li" );
    // and here
    liElement.classList.add ( "card-in-hand" );
    liElement.style.width = "75px";
    liElement.style.height = "150px";

    liElement.appendChild ( imgElement );
    hand.appendChild ( liElement );
  }
}

When I use chrome's inspector the the classes show up as you would expect under the element properties, however the actual css class values aren't populated. When I try to just embed this directly as html it works as expected.

Why does this not work specifically in Angular?

Earleking
  • 69
  • 8
  • have you set the styles in `card-img-style` to `!important`? Did you put the hight and width in `card-in-hand` and add `!important`? – Train Nov 11 '19 at 20:27
  • I am setting the display property in my css so there should not be a conflict like that. But I did try adding the !important flag and it still fails. – Earleking Nov 11 '19 at 20:33

1 Answers1

0

Found the answer. Elements generated by Angular on initial render have the property _ngcontent-cX. The X is a number. It also changes all css classes so that they only apply to elements with this property. I assume the c stands for component and this is to prevent collision in CSS between components. Useful, but also very annoying if you are trying to generate html dynamically.

To get around this you can set:

@Component({
  selector: 'my-comp',
  encapsulation: ViewEncapsulation.None,
  ...
});

This removed that attribute and allows you to easily generate html with styling.

Answer gotten from this stackoverflow answer

Earleking
  • 69
  • 8