2017-02-07 94 views
0

我有一個組件,其特點是一組3個自定義按鈕,我想將這些按鈕用作錄音機的控件。根據它們的功能,我陷入了第一階段,我想要更改按鈕上顯示的符號。我試圖通過改變它們的xlink:href屬性(我使用svg)來實現,但是在控制檯EXCEPTION: Error in ./RecordComponent class RecordComponent - inline template:5:45 caused by: this.roundButtonOne.getAttribute is not a function中獲得了這個。任何想法爲什麼以及如何用Angular2方法來實現?下面是代碼:角2更改屬性

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

如果你調用按鈕元素之一的console.log,你可以看到它是實例ElementRef,不HTML元素

所以......

導入ElementRef從@角/核心:

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

更改按鈕從HTML元素到ElementRef類型:

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

獲取nativeElementElementRef對象然後調用setAttribute()/的getAttribute()方法

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

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

謝謝你,它的工作! –