问题
I have a component which features a set of 3 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 Angular2 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>
</div>
`
})
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');
}
}
回答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');
回答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 #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
来源:https://stackoverflow.com/questions/42097796/angular-2-change-attributes