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

时间:2015-12-29 19:44:27

标签: angular

我正在编写一个需要访问<audio controls>本机元素的组件。我现在通过使用ngOnInit() ElementRef this.elementRef.nativeElement.querySelector("audio");<audio controls #player>来实现这样做this.player

虽然它有效,但我认为它非常不优雅,Angular2也warns of the risks when using ElementRef ..

真的没有更简单的方法吗?

我可以将它标记为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"); } } 的局部变量,并以某种方式通过module.exports = function (grunt) { grunt.initConfig({ pkg: grunt.file.readJSON("package.json"), copy: { main: { files: [ { expand: true, flatten: true, src: [ 'node_modules/vss-sdk/lib/VSS.SDK.js', 'node_modules/moment/moment.js', 'node_modules/moment-timezone/moment-timezone.js', 'node_modules/jquery/dist/jquery.js', 'bower_components/datetimepicker/jquery.datetimepicker.js', 'bower_components/datetimepicker/jquery.datetimepicker.css', ], dest: 'scripts/lib', filter: 'isFile' } ] } } }); grunt.loadNpmTasks("grunt-exec"); grunt.loadNpmTasks("grunt-contrib-copy"); }; 或类似的控制器访问本机元素吗?

{{1}}

1 个答案:

答案 0 :(得分:59)

  1. 使用@ViewChild访问视图中的某个元素。
  2. 使用[attr.src]创建对元素'src'属性的绑定。
  3. 如果出于某种原因需要更改DOM,请使用Renderer
  4. 请参阅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);
      }
    }