angularangular2-directivesangular-renderer2

Angular accessing function specified in renderer2 set property


I have a directive that replaces a table value with an "a href" using renderer.setProperty.

Attached to the "a href" is a "click" property which im not sure how to access the function: "onClickAccountLink($event)" or add a programmatic function to it.

I've tried adding the same function name within the same directive but it does not seem to use the same function specified in the same file.

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

@Directive({
  selector: '[AccountLink]'
})
export class AccountLink implements OnInit {

  constructor(public el: ElementRef, public renderer: Renderer2) {}

  ngOnInit() {}
  ngAfterViewInit() {
    let iban = this.el.nativeElement;
    if(iban) {
      this.format(iban);
    }
  }

  format(val) {
    this.renderer.setProperty(val, 'innerHTML', `<a href="javascript: void(0)" (click)="onClickAccountLink($event)">${val.innerHTML}</a>`);
    console.log(typeof(val.innerHTML)) //string
    

  }

  onClickAccountLink(event: any) {
    console.log(event)
    event.stopPropagation();
    event.preventDefault();
    console.log("function called")
  }
}

the directive is attached to a value in a table row.

<td AccountLink>{{iban}}</td>

how do I make my onClickAccountLink function usable?


Solution

  • i read this problem and it solved my problem.

    i added the "render.listen" to check for the click event

      format(ibanValue) {
        this.renderer.setProperty(ibanValue, 'innerHTML', `<a href="javascript: void(0)">${ibanValue.innerHTML}</a>`);
        this.renderer.listen(ibanValue ,'click', ()=> {
          this.onClickAccountLink(ibanValue);
        });
      }