【问题标题】:How to get bradmartin/nativescript-videoplayer element reference in my component using @viewChild?如何使用@viewChild 在我的组件中获取 bradmartin/nativescript-videoplayer 元素引用?
【发布时间】:2017-06-28 13:02:16
【问题描述】:

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

【问题讨论】:

    标签: typescript nativescript angular2-nativescript


    【解决方案1】:

    检查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();
        }
    }
    

    【讨论】:

    • 感谢您的回答。我有一个问题,我正在尝试使用字符串更改源,就像您在src 一样。我正在从 firebase 下载 url 并将其应用于字符串,但它不起作用。尽管使用硬编码的 url 工作正常。通过使用 viewchild,this.videoPlayer.src = newSource 可以正常工作。我很好奇直接更改src有什么问题?
    • 感谢您的回复。我尝试使用 ViewChild 并且成功了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-18
    • 1970-01-01
    • 2017-05-07
    • 1970-01-01
    • 2018-08-14
    • 2017-05-25
    • 2019-01-20
    相关资源
    最近更新 更多