4

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
Mike Poole
  • 1,958
  • 5
  • 29
  • 41
  • 1
    Why don't you use `this.renderer.setAttribute`? You can use `this.renderer.listen` for this. – Ivan Feb 19 '19 at 16:03
  • If you use `element.setAttribute` then it should be `onclick`, not `(click)`. And the proper way is using `renderer.setAttribute` as mentioned by @Lends – amedina Feb 19 '19 at 16:04
  • `(click)` isn't a valid attribute name anyway – Ivan Feb 19 '19 at 16:06

2 Answers2

2

(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');
      })
    }
Yahya Essam
  • 1,832
  • 2
  • 23
  • 44
2

You can use the Renderer2 to add attributes and event listeners. I think it is better to use the Renderer2 since it acts like a wrapper and abstracts how the DOM manipulation works under the hood.

 const element = this.renderer.createElement('a');
 this.renderer.setAttribute(element, 'href', 'foobar');
 this.renderer.listen(element, 'click', this.myMethod);

Here is a working example

John
  • 10,165
  • 5
  • 55
  • 71