Angular 2更改属性 [英] Angular 2 change attributes
问题描述
我有一个组件,该组件具有一组3个自定义按钮,我想将这些按钮用作录音机的控件.我陷入了第一阶段,在那里我想根据按钮的功能更改按钮上显示的符号.我试图通过更改它们的xlink:href属性(我使用svg)来实现这一点,但是在控制台EXCEPTION: Error in ./RecordComponent class RecordComponent - inline template:5:45 caused by: this.roundButtonOne.getAttribute is not a function
中得到了它.知道为什么以及如何使用Angular2方法实现这一点吗?这是代码:
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');
}
}
推荐答案
如果在按钮元素之一上调用 console.log ,您会看到它是 ElementRef的实例. ,而不是 HTMLElement .
If you call console.log on one of the button elements, you can see that it is an instance of ElementRef, not HTMLElement.
所以...
从@ angular/core导入ElementRef:
Import ElementRef from @angular/core:
import {Component, ViewChild, ElementRef} from '@angular/core';
将按钮类型从HTMLElement更改为ElementRef:
Change the buttons type from HTMLElement to ElementRef:
@ViewChild('roundButtonOne') roundButtonOne: ElementRef;
@ViewChild('roundButtonTwo') roundButtonTwo: ElementRef;
@ViewChild('roundButtonThree') roundButtonThree: ElementRef;
从 ElementRef 对象获取 nativeElement ,然后调用 setAttribute()/ getAttribute()方法:>
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');
这篇关于Angular 2更改属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!