How to change attributes

If you call console.log on one of the button elements, you can see that it is an instance of ElementRef, not HTMLElement.

So...

Import ElementRef from @angular/core:

import {Component, ViewChild, ElementRef} from '@angular/core';

Change the buttons type from HTMLElement to ElementRef:

@ViewChild('roundButtonOne') roundButtonOne: ElementRef;
@ViewChild('roundButtonTwo') roundButtonTwo: ElementRef;
@ViewChild('roundButtonThree') roundButtonThree: ElementRef;

Get nativeElement from ElementRef object and then call setAttribute() / getAttribute() methods:

this.roundButtonOne.nativeElement.getAttribute('xlink:href');

this.roundButtonOne.nativeElement.setAttribute('xlink:href','#mic-small');

You also can use direct property of Element like src, href, text.

TS

this.link.nativeElement.href = 'microsoft.com';
this.link.nativeElement.text = 'Microsoft';
this.myimage.nativeElement.src = 
   'https://cdn0.iconfinder.com/data/icons/flowers-and-leaves/42/flower_2-512.png';

HTML

<img #myimage width="100px" 
             src="https://cdn4.iconfinder.com/data/icons/nature-20/512/79-512.png" />
<a #mylink href="google.com">Google</a>
<br>
<button (click)="change()">Change</button>

Demo https://stackblitz.com/edit/angular-set-attribute-element?file=src/app/app.component.html

Tags:

Html

Angular