Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying styles to dynamically created elements in Angular 2

I've used the Angular CLI to generate a new component which has given me a HTML file, CSS file and a typescript file. In the typescript file I'm generating some HTML (two divs) to wrap some tweets that are generated by a JS file.

ngOnInit() {
    var config = {
      "id": '605465000484982784',
      "domId": '',
      "maxTweets": 3,
      "enableLinks": true,
      "showUser": false,
      "showTime": true,
      "dateFunction": '',
      "showRetweet": false,
      "customCallback": handleTweets,
      "showInteraction": false
    };

    function handleTweets(tweets) {
        var x = tweets.length;
        var n = 0;
        var element = document.getElementById('social');
        var html = '';
        while(n < x) {
          html += '<div class="tweet-outer"><div class="tweet-inner">' + tweets[n] + '</div></div>';
          n++;
        }
        element.innerHTML = html;
    }

    twitterFetcher.fetch(config);
  }

But the tweet-outer and tweet-inner css styles are not being applied. I'm 99% sure this is due to how the styles load in Angular, but I just don't know how to to get round it, I'm also pretty sure it's gonna be something really simple to fix it, but it seems like there's so many different ways to fix CSS issues in Angular that I feel like I'm just lost in a sea of different solutions!

like image 439
Web Develop Wolf Avatar asked Nov 29 '22 08:11

Web Develop Wolf


1 Answers

For your dynamically created classes you can style them like this

:host::ng-deep .yourclassnamehere {

}

you can reference this post Angular 2 - innerHTML styling for more information

EDIT: 23/05/2019

The ::ng-deep pseudo-class selector also has a couple of aliases: >>> and /deep/, and all three are soon to be removed.

https://github.com/angular/angular/issues/25160

The situation is still evolving, but right now, ::ng-deep can be used if needed for certain use cases.

In most cases, adding your styles to your global style sheet will solve this issue

like image 52
Smokey Dawson Avatar answered Dec 06 '22 12:12

Smokey Dawson