How to use nativescript's WebView in angular2?

2020-03-28 04:20发布

问题:

I'm trying to insert a web-view on my page and listen the 'loadFinishedEvent'... But for do this, i need to find the webview in my component (ts file), through nativescript way i need to wrap my xml (UI) with a tag:

<Page xmlns="http://schemas.nativescript.org/tns.xsd

But doing this i got this error: "TypeError: this.page.frame._getNavBarVisible is not a function", and without the Page tag i've already tried with some ways but with unsuccessful...

I do not found any sample of this too, can anyone help me?

回答1:

Your .ts file containing class implementation

import { Component } from "@angular/core";

@Component({
selector: "Date",
templateUrl: "myPage.html", //here is your reference to html page
})

export class Angular2WebView {
//any class function
}

Your html file myPage.html

<GridLayout>
    <WebView id="webView" url="http://www.google.com" >
    </WebView>
</GridLayout>

for more info. refer here Nativescript bare webview doesnt seem to work



回答2:

Good link for documentation for using WebView Nativescript/Android

html:

 <WebView #webview [src]="url"></WebView>

backend code:

import {Component, OnInit} from "@angular/core";
import {WebView, LoadEventData} from "ui/web-view";

@Component({
    selector: 'basic-web-view-component',
    templateUrl: //see html above
})

export class BasicWebViewComponent implements OnInit {

    public url="https://www.google.com";
    @ViewChild("webview") webview: WebView;

    ngOnInit() {

        this.webview.on(WebView.loadFinishedEvent, function (args: LoadEventData) {
             console.log("loadFinishedEvent called");
        });
    }
}

Note: that it seems that WebView needs to sized with width/height attributes are in a GridView, see the docs reference above. It won't dynamically grow based on content.



回答3:

I solved it with the following code:

<WebView [src]="url" (loadFinished)="loadFinished($event)"></WebView>

Important: remove the <Page> tag (should not be used within Nativescript/Angular 2).

More info: github issue



回答4:

Have you tried to use the eventargs on load with the method getViewById to find a control. You can find more information here - https://docs.nativescript.org/ui/ui-with-xml