如何更改属性 [英] How to change attributes

查看:60
本文介绍了如何更改属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组件,它具有一组三个自定义按钮,我想将这些按钮用作录音机的控件.

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.

我试图通过更改其 xlink:href 属性(我使用svg)来实现这一点,但可以在控制台中找到它:

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

有人知道为什么以及如何使用Angular方法来实现吗?这是代码:

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

推荐答案

如果您对其中一个按钮元素调用 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');

这篇关于如何更改属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆