加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

从Angular2中的控制器中的模板访问局部变量

发布时间:2020-12-17 08:26:23 所属栏目:安全 来源:网络整理
导读:我正在编写一个组件,我需要访问 audio controls原生元素。我现在这样做,现在通过使用这个this.elementRef.nativeElement.querySelector(“audio”)的ElementRef获取它在ngOnInit(); 虽然它的作品我认为这是非常不安,Angular2也是warns of the risks when
我正在编写一个组件,我需要访问< audio controls>原生元素。我现在这样做,现在通过使用这个this.elementRef.nativeElement.querySelector(“audio”)的ElementRef获取它在ngOnInit();

虽然它的作品我认为这是非常不安,Angular2也是warns of the risks when using ElementRef ..

真的没有简单的方法吗?

我可以将其标记为带有< audio controls#player>的局部变量。并以某种方式通过this.player访问本机元素或类似于控制器的东西?

import {Component,OnInit,ElementRef,Input} from 'angular2/core';

@Component({
    selector: 'audio-preview',template: `
        <audio controls>
            <source [src]="src" type="audio/mpeg">
            Your browser does not support the audio element.
        </audio>
    `
})

export class AudioPreview implements OnInit {

    @Input() src: string;

    constructor(public elementRef: ElementRef) {}

    ngOnInit() {
        var audioElement = this.getAudioElement();
        audioElement.setAttribute('src',this.src);
    }

    getAudioElement() : HTMLAudioElement {
        return this.elementRef.nativeElement.querySelector("audio");
    }
}
>使用 @ViewChild访问视图中的某些元素。
>使用 [attr.src]创建绑定到元素的“src”属性。
>如果由于某种原因需要更改DOM,请使用 Renderer

见this plunk。

import {Component,Input,ViewChild,Renderer} from 'angular2/core';

@Component({
  selector: 'audio-preview',template: `
    <audio controls #player [attr.src]="src">
      <source [src]="src" type="audio/mpeg">
      Your browser does not support the audio element.
    </audio>
    `
})
export class AudioPreview {
  @Input() src: string;
  @ViewChild('player') player;

  constructor(public renderer: Renderer) {}

  ngAfterViewInit() {
    console.log(this.player);

    // Another way to set attribute value to element
    // this.renderer.setElementAttribute(this.player,'src',this.src);
  }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读