Skip to content Skip to sidebar Skip to footer

How To Change Attributes

I have a component which features a set of three custom buttons and I want to use these buttons as controls for a sound recorder. I got stuck in the first phase, where I want to ch

Solution 1:

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');

Solution 2:

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 #myimagewidth="100px"src="https://cdn4.iconfinder.com/data/icons/nature-20/512/79-512.png" /><a #mylinkhref="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

Post a Comment for "How To Change Attributes"