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?
To create a custom directive we have to replace @Component decorator with @Directive decorator. So, let's get started with creating our first Custom Attribute directive. In this directive, we are going to highlight the selected DOM element by setting an element's background color. Create an app-highlight.
If we go by the Angular definition, a factory component Angular is a base class for a factory that can create a component dynamically. Instantiate a factory for a given type of component with resolveComponentFactory(). Use the resulting ComponentFactory. create() method to create a component of that type.
To add the component to the template, you call createComponent() on ViewContainerRef .
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. 😊🤔
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With