Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: Add directive to dynamically created component(s)

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?

like image 870
Anvith Avatar asked Mar 19 '18 14:03

Anvith


People also ask

How do I add a directive to a 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.

Can we create component dynamically in Angular?

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.

Which of the following directives is used to add a component at runtime in angular5?

To add the component to the template, you call createComponent() on ViewContainerRef .


1 Answers

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. 😊🤔

like image 175
Shy Agam Avatar answered Oct 21 '22 15:10

Shy Agam