How to get/set/remove element attribute in Angular 2 using "the angular way"?

To remove attributes from the DOM you provide a value of null.

To set an attribute (attribute value can be an empty string if you wish):

myrenderer.setElementAttribute(elementRef.nativeElement, 'attributename', 'attributevalue');

To remove an attribute:

myrenderer.setElementAttribute(elementRef.nativeElement, 'attributename', null);

To get an element attribute value, you have the nativeElement which you pass to setElementAttribute, so you can use that to get the attribute value using standard Javascript:

elementRef.nativeElement.getAttribute('attributename');

In case someone is still looking for this (as I did), i shall add up a bit on David's answer which was on Angular's native renderer.

You have all this requested functionality in newest Angular Renderer2

Particularly if you want to completely remove attributes (ex. invalid aria tags in community components that fail accessibility tests) from elements and not set their value to null, there is

renderer2.removeAttribute(elementRef.nativeElement, 'AttributeName');

EDIT: You should use AfterViewInit() lifecycle, as described in other answers, as the initial view must be rendered before you make any custom DOM changes.


Angular2 doesn't provide any support to get anything from the DOM except ElementRef and events.
The Angular2 way is to maintain the state in the model and update the DOM to reflect that state.

If you need to read from the DOM you can use direct DOM access or provide a custom Renderer that provides the features you're missing in the default Renderer.

Examples for custom renderers

  • Custom renderer for Angular2
  • https://github.com/ralfstx/angular2-renderer-example/blob/master/src/custom-renderer.ts

Tags:

Angular