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
3
  • 1
    Why don't you use this.renderer.setAttribute? You can use this.renderer.listen for this. Commented Feb 19, 2019 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 Commented Feb 19, 2019 at 16:04
  • (click) isn't a valid attribute name anyway Commented Feb 19, 2019 at 16:06

2 Answers 2

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');
      })
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Many thanks for that @Yahya Essam, it got me on the right track.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.