18

I came across the following Plunker to dynamically add and remove components. According to the above link and from many other SO posts, I know how to access Input and Output properties:

this.compRef.instance.someProperty = 'someValue';
this.compRef.instance.someOutput.subscribe(val => doSomething()); 

And I also have a directive "appFont".

import { Directive, ElementRef } from '@angular/core';

@Directive({
  selector: '[appFont]'
})
export class HighlightDirective {
    constructor(el: ElementRef) {
       el.nativeElement.style.font = 'Calibri';
    }
}

How do I add this "appFont" directive to the new dynamically created component?

syam
  • 799
  • 1
  • 12
  • 30
Anvith
  • 477
  • 9
  • 22
  • 1
    Does this answer your question? [How to instantiate and apply directives programmatically?](https://stackoverflow.com/questions/39563547/how-to-instantiate-and-apply-directives-programmatically) – satanTime Feb 27 '21 at 21:00
  • This can be helpful. [How to dynamically add a directive?](https://stackoverflow.com/questions/41298168/how-to-dynamically-add-a-directive) – Berkin Sansal Feb 04 '22 at 08:40

1 Answers1

3

A directive is first a class.

If you can manually get your hands on the stuff the constructor needs, you can simply do something like:

const highlight = new HighlightDirective(...);

❗ Note that this is not standard Angular code. It is almost always preferable to let Angular do the work for you as you might accidentally escape its pipes and go rogue. If that happens, you might run into unexpected Angular behaviors as Angular doesn't know about what you're doing...

A 3 year old question... I wonder if anyone is still trying to achieve this.

Shy Agam
  • 1,285
  • 1
  • 13
  • 37