0

I'm using a directive to inject HTML dynamically to other HTML elements, specifically to other components in which i can't modify the code. My issue is that if i inject HTML elements in which they call a local function from the same component they don't work. An example of this:

<button class="button-default" (click)="showTable()">Show table info</button>

In this case, doesn't happen nothing if you press the button, the function is not called.

The directive code:

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


@Directive({
    selector: '[insertHtml]'
})

export class InsertHtml {

    @Input()   targetHtml : string;
    @Input()   html : string;
    @Input()   position: any;

    private el: HTMLInputElement;
    constructor(private elementRef: ElementRef) { 
        this.el = this.elementRef.nativeElement;  

    }



  ngAfterViewInit() {

        let target = this.el.querySelector(this.targetHtml );
        target.insertAdjacentHTML(this.position, this.html);

    }
}

How it works the directive:

<div class="block" [insertHtml]="'ul.nav.nav-tabs'" [html]="htmlButtons" [position]="'afterend'">

htmlButtons would be code i put in the example case.

How i can make the function inside of the injected HTML elements work?

Progs
  • 1,059
  • 7
  • 27
  • 63
  • please show a full picture how the method and the containing component and directives are laid out in your code? Or better make a reproduction. Thanks – amal Sep 24 '18 at 19:18
  • 1
    You may find ideas in [this post](https://stackoverflow.com/q/41609937/1009922). – ConnorsFan Sep 24 '18 at 19:32
  • @ConnorsFan Looks like a workaround but i take it – Progs Sep 24 '18 at 19:39
  • I think only workarounds can work, as mentioned in [this other answer](https://stackoverflow.com/a/37936094/1009922). – ConnorsFan Sep 24 '18 at 19:51
  • @ConnorsFan what about if i need to use *ngIf ,ngClass or similar directives? – Progs Sep 24 '18 at 20:01
  • If you avoid inserting the HTML directly, but use Angular structural directives (`ngIf`, `ngFor`), templates or components instead, event binding should work, yes. These are the way to work with Angular. – ConnorsFan Sep 24 '18 at 20:16

0 Answers0