instantiate angular custom directive from angular component on click

276 Views Asked by At

Assume I have a directive with name 'my-custom-directive' and component with name 'app.component' I have a method in app.component - createDirective() that will be invoked on click of a button from app-component.html I want to instantiate my-custom-directive from this method. how can this be done in angular2 & above?

I tried with Renderer2 but unable create directive from component

1

There are 1 best solutions below

0
On
import { Directive, HostListener } from '@angular/core';

@Directive({
  selector: '[my-custom-directive]'
})
export class MyCustomDirective {

  constructor() { }

  @HostListener('click', ['$event']) onClick($event: Event) {
    // Do what ever you want to do ....
  }
}

// In Your Component HTML : 
<button my-custom-directive></button>

// Don't forget to include the references in your Module.
// See if this Solves your purpose.