单击按钮时,在 Nativescript + Angular 的 TimePicker 小部件中获取小时和分钟

Get the hours and minutes in TimePicker widget in Nativescript + Angular when click in a button

Nativescript Timepicker documentation 说我可以同时使用 loadedtimeChange 事件来与日期进行交互。

但是我需要在用户按下提交按钮时获取时间。你能给我一些实现这一目标的指导方针吗?我使用 @ViewChild 通过引用获取元素,尽管这似乎不是正确的方法。

您可以使用 @ViewChild 获取对您的 TimePicker 的引用并读取当前时间值。不过,如果您愿意,您也可以直接使用本机 loaded 事件来实现相同的目的。

使用来自 loaded 事件的引用的示例

时间-picker.component.html

<StackLayout class="home-panel">
    <TimePicker #tp (loaded)="onTimePickerLoaded($event)" 
                [hour]="currentHour" [minute]="currentMinute" 
                verticalAlignment="center"></TimePicker>
    <Button text="Submit" (tap)="onSubmit()"></Button>
</StackLayout>

时间-picker.component.ts

import { Component } from "@angular/core";
import { TimePicker } from "tns-core-modules/ui/time-picker";

@Component({
    selector: "time-picker",
    moduleId: module.id,
    templateUrl: "./time-picker.component.html"
})
export class HomeComponent {
    currentHour: number = new Date().getHours();
    currentMinute: number = new Date().getMinutes();
    timePicker: TimePicker;

    onTimePickerLoaded(args) {
        this.timePicker = args.object as TimePicker;
    }

    onSubmit(): void {
        console.log("Submit was pressed");

        console.log(this.timePicker.time);
        console.log(this.timePicker.hour);
        console.log(this.timePicker.minute);
    }
}

Playground demo for the above scenario.

另一种可能是通过 getViewById 和页面 DI 获取引用。

页面依赖注入示例

时间-picker.component.html

<StackLayout class="home-panel">
    <TimePicker #tp id="my-time-picker" (loaded)="onTimePickerLoaded($event)" 
                [hour]="currentHour" [minute]="currentMinute" 
                verticalAlignment="center"></TimePicker>
    <Button text="Submit" (tap)="onSubmit()"></Button>
</StackLayout>

时间-picker.component.ts

import { Component } from "@angular/core";
import { TimePicker } from "tns-core-modules/ui/time-picker";
import { Page } from "tns-core-modules/ui/page";

@Component({
    selector: "Home",
    moduleId: module.id,
    templateUrl: "./time-picker.component.html",
})
export class HomeComponent {
    currentHour: number = new Date().getHours();
    currentMinute: number = new Date().getMinutes();

    timePicker: TimePicker;

    constructor(private _page: Page) { 
        this._page.on("loaded", () => { 
            this.timePicker = this._page.getViewById("my-time-picker");
        })
    }

    onSubmit(): void {
        console.log("Submit was pressed");

        console.log(this.timePicker.time);
        console.log(this.timePicker.hour);
        console.log(this.timePicker.minute);
    }
}

Playground demo for the above example