3
votes

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.

1
could you modify the data in htmlToInsert and add the color as an inline style? <a style="color: yourDynamicColor"></a> - LLai
@LLai I could possibly modify it using a pipe. - TheSoundDefense
How do you get htmlToInsert? Could you possibly edit that value somewhere in your component.ts code - LLai
@LLai I could, but that would be a pretty hacky solution and I have been advised against it. - TheSoundDefense
The simple solution you need to follow is stackoverflow.com/a/57973805/7540573 - Sahil Ralkar

1 Answers

1
votes

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