angularrendererelementref

Setting (click) Attribute on Anchor Element


As I understand it it is not possible to dynamically add a '(click)' attribute to an element of the DOM using Renderer2 in Angular 2+.

If this is true how do you lovely people add a '(click)' attribute when they are dynamically creating HTML in the component or what workaround do you use?

 const element = this.renderer.createElement('a');

 element.setAttribute('href', 'foobar');     // This works
 element.setAttribute('(click)', 'foobar');  // This does not work

Solution

  • (click) is not an attribute and you can't use it like this.
    you may use .addEventListener
    for example
    element.addEventListener('click', function(){ do something} );



    if you want full angular example :
    HTML

    <button #mybtn>my Button</button>
    

    TS

     @ViewChild('mybtn') myBtn:ElementRef;
        ngOnInit() {
          this.myBtn.nativeElement.addEventListener('click', function() {
           console.log('from there');
          })
        }