Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying dynamic styling to injected HTML in Angular 2

Tags:

css

angular

For an Angular project I'm working on, I'm injecting HTML into a <div> like so:

<div class="myClass" [innerHTML]="htmlToInsert"></div>

The htmlToInsert contains a variety of things, notably <a> tags. Previously we were styling all these tags like so:

.myClass ::ng-deep a {
  color: #f00;
  text-decoration: none;
}

And this worked fine. But now I need the color of these links to be dynamically generated during component initialization, based on data coming in from elsewhere. All of the dynamic styling I've seen in Angular requires you to apply things directly to the HTML tag, but we don't have them here to work with.

How can I apply dynamic styling to HTML that is also dynamically generated? Can I directly change the CSS class somehow? Would using a pipe be the correct approach here? Is there another method I don't know about? I could maybe refactor code if there is absolutely no other way of doing this.

like image 941
TheSoundDefense Avatar asked Jun 24 '26 22:06

TheSoundDefense


1 Answers

So if you can't modify the innerHTML you are passing in, you can achieve this functionality with a custom directive. Essentially you would tag your div that contains your innerHTML with a custom directive. That directive then looks for any anchor tags in it and changes the color based on an input.

// component.html
<div anchorColor [color]="dynamicColor" [innerHTML]="htmlToInsert"></div>

// directive.ts
@Directive({selector: '[anchorColor]'})
export class AnchorColorDirective implements OnAfterViewInit {
    @Input() color: string;

    constructor(private el: ElementRef){
    }

    // afterViewInit lifecycle hook runs after DOM is rendered
    ngAfterViewInit(){
        // get anchor element
        let anchorEl = this.el.nativeElement.querySelector('a');
        // assign color
        if(anchorEl){
            anchorEl.style.color = this.color;
        }
    }
}

Here is a working plunkr https://plnkr.co/edit/QSYWSeJaoUflP94Cy4Hm?p=preview

like image 60
LLai Avatar answered Jun 27 '26 13:06

LLai