如何使用@viewChild在我的组件中获取bradmartin / nativescript-videoplayer元素引用?

时间:2017-06-28 13:02:17

标签: typescript nativescript angular2-nativescript

Reference to the third party player on github.

问题:

如何使用viewChild获取组件中第三方nativescript-videoplayer的元素引用?

错误:

当我尝试通过this.videoPlayer.play()

尝试访问方法时,我的代码会编译但崩溃
  

TypeError:this.videoPlayer.play不是函数。 (在   ' this.videoPlayer.play()',' this.videoPlayer.play'   未定义)

代码:

player.component.ts

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

import {registerElement} from "nativescript-angular/element-registry";
registerElement("VideoPlayer", () => require("nativescript-videoplayer").Video);

@Component({
    selector: "Player",
    moduleId: module.id,
    templateUrl: "./player.component.html",
    styleUrls: ["./player.component.css"]
})
export class PlayerComponent implements OnInit{

    @ViewChild("video_player") videoPlayer: Video;

    public src: string = "<YOUR VIDEO URL HERE>"

    ngOnInit(): void {
        this.videoPlayer.play();
    }
}

player.component.html

        <VideoPlayer
                #video_player
                [src]="src"
                height="300"></VideoPlayer>

github issue reference #77

1 个答案:

答案 0 :(得分:2)

通过以下方式检查this.videoPlayer的属性:

for(let prop in this.videoPlayer){
  if(this.videoPlayer.hasOwnProperty(prop)){
    console.dir(prop);
  }
}

我注意到它只有一个属性“nativeElement”。为了能够使用它,我必须将viewChild类型从“Video”更改为“ElementRef”,这样我才能访问nativeElement,然后允许我访问所有API是在文档中定义的。

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

import {registerElement} from "nativescript-angular/element-registry";
registerElement("VideoPlayer", () => require("nativescript-videoplayer").Video);

@Component({
    selector: "Player",
    moduleId: module.id,
    templateUrl: "./player.component.html",
    styleUrls: ["./player.component.css"]
})
export class PlayerComponent implements OnInit{

    @ViewChild("video_player") videoPlayer: ElementRef;

    public src: string = "<YOUR VIDEO URL HERE>"

    ngOnInit(): void {
        this.videoPlayer.nativeElement.play();
    }
}