Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change attributes

Tags:

html

angular

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 change the symbols displayed on the buttons, according to their function.

I tried to achieve that by changing their xlink:href attributes (I use svg), but got this in he console:

EXCEPTION: Error in ./RecordComponent class RecordComponent - inline template:5:45 caused by: this.roundButtonOne.getAttribute is not a function

Any idea why and how I could implement this with an Angular approach? Here is the code:

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

@Component({
  selector: 'app-record',
  template: `
    <svg class='roundButtonOne icon'>
      <use #roundButtonOne xlink:href='#mic'(click)='onRecord()'/>
    </svg>
    <svg class='roundButtonTwo icon'>
      <use #roundButtonTwo xlink:href='#live' />
    </svg>
    <svg class='roundButtonThree icon'>
      <use #roundButtonThree xlink:href='#upload' />
    </svg>
    `
})
export class RecordComponent {

  private recording: boolean = false;

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

  onRecord() {
    this.recording = true;

    switch(this.roundButtonOne.getAttribute('xlink:href')) {
      case '#mic':
        this.record();
        break;
    }
  }

  record() {
    this.roundButtonOne.setAttribute('xlink:href','#mic-small');
    this.roundButtonTwo.setAttribute('xlink:href', '#pause');
    this.roundButtonThree.setAttribute('xlink:href', '#stop');
  }
}
like image 884
Radu Miron Avatar asked Feb 07 '17 18:02

Radu Miron


1 Answers

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');
like image 105
pan.goth Avatar answered Sep 20 '22 22:09

pan.goth