Можно ли использовать ListView в SideDrawer в NativeScript?

Мне нужно реализовать SideDrawer в NativeScript с элементами меню, которые могут динамически меняться в зависимости от некоторых условий.

Я решил использовать ListView для отображения пунктов меню, потому что список может быть длинным и, вероятно, потребуется прокрутка.

Тем не менее, я не могу заставить его работать, и я не могу найти причину. Документация по NativeScript для Angular немного неполная, и я не уверен, что правильно собираю части.

SideDrawer работает правильно, но ListView не отображается. Обратите внимание, что если я добавляю элементы, используя StackLayout вместо ListView, они отображаются.

Это шаблон, над которым я работаю:

<ActionBar title="Inline" >
    <NavigationButton [visibility]="hideDrawer || (isAndroid ? 'visible' : 'collapse')" icon="res://ic_menu" (tap)="onDrawerTap()"></NavigationButton>
    <ActionItem [visibility]="hideDrawer || (isAndroid ? 'collapse' : 'visible')" icon="res://ic_menu" ios.position="right" (tap)="onDrawerTap()"></ActionItem>
</ActionBar>

<RadSideDrawer #drawer>

    <StackLayout tkDrawerContent class="sideStackLayout">

        <GridLayout>
            <RadListView [items]="menuEntries" orientation="vertical">
                <template tkListItemTemplate let-item="item">
                    <StackLayout>
                        <Label [text]="item.label"  class="sideLabel"></Label>
                    </StackLayout>
                </template>
            </RadListView>
        </GridLayout>

    </StackLayout>

    <StackLayout tkMainContent>



    </StackLayout>

</RadSideDrawer>

и это код компонента, я удалил неактуальную логику:

import * as application from "application";
import { Component, ViewChild, OnInit } from "@angular/core";
import { RadSideDrawerComponent, SideDrawerType } from "nativescript-telerik-ui/sidedrawer/angular";
import * as applicationSettings from "application-settings";

class MenuEntry {
    constructor(
        public label: string,
        public url: string
    ){}
}

@Component({
    selector: "main-container",
    templateUrl: 'app.component.html',
    styleUrls: ['app.component.css']

})
export class AppComponent implements OnInit {

    @ViewChild(RadSideDrawerComponent)
    public drawerComponent: RadSideDrawerComponent;
    private drawer: SideDrawerType;
    isAndroid:boolean = application.android !== null;
    hideDrawer = false;
    menuEntries:Array<MenuEntry> = [];

    constructor() {}

    ngAfterViewInit() {
        this.drawer = this.drawerComponent.sideDrawer;
    }

    public onDrawerTap() {
        this.drawer.toggleDrawerState();
    }

    public closeDrawer(){
        this.drawer.closeDrawer();
    }

    ngOnInit(){
        this.generateMenu();
    }

    private generateMenu(): void {
        this.menuEntries.push(
            new MenuEntry("LABEL1", "/place1"),
            new MenuEntry("LABEL2", "/place2")
        );
    }


}

Я использую:

  • родной скрипт: 2.2.1
  • родной скрипт-угловой: 0.3.1
  • родной скрипт-телерик-уи: 1.3.1

Какие-либо предложения?

Спасибо


comment
Вы уверены, что добавили LISTVIEW_PROVIDERS в вызов nativeScriptBootstrap, он показан здесь github.com/telerik/nativescript-ui-samples-angular/blob/release/?   -  person Vladimir Amiorkov    schedule 11.09.2016
comment
@VladimirAmiorkov, конечно, это была проблема. Спасибо за предложение!   -  person Giordano    schedule 12.09.2016


Ответы (1)


Чтобы иметь возможность использовать оба компонента SideDrawer и RadListview, вы должны сначала добавить NativeScriptUISideDrawerModule и NativeScriptUIListViewModule в импорт в файле app.module.ts. Для получения дополнительной информации о том, как использовать ListView внутри SideDrawer, просмотрите приведенный ниже пример.

app.module.ts

import { NgModule, NO_ERRORS_SCHEMA } from "@angular/core";
import { NativeScriptModule } from "nativescript-angular/nativescript.module";
import { AppRoutingModule } from "./app.routing";
import { AppComponent } from "./app.component";

import { ItemService } from "./item/item.service";
import { ItemsComponent } from "./item/items.component";
import { ItemDetailComponent } from "./item/item-detail.component";
import { NativeScriptUIListViewModule } from "nativescript-telerik-ui-pro/listview/angular";
import { NativeScriptUISideDrawerModule } from "nativescript-telerik-ui-pro/sidedrawer/angular";
@NgModule({
    bootstrap: [
        AppComponent
    ],
    imports: [
        NativeScriptModule,
        AppRoutingModule,
        NativeScriptUIListViewModule,
        NativeScriptUISideDrawerModule
    ],
    declarations: [
        AppComponent,
        ItemsComponent,
        ItemDetailComponent
    ],
    providers: [
        ItemService
    ],
    schemas: [
        NO_ERRORS_SCHEMA
    ]
})
export class AppModule { }

items.component.html

<GridLayout rows="" columns="">
<RadSideDrawer #drawer>
    <StackLayout tkDrawerContent class="sideStackLayout" backgroundColor="red">
        <StackLayout class="sideTitleStackLayout" >
            <Label text="Navigation Menu"></Label>
        </StackLayout>
        <GridLayout class="sideStackLayout">
            <RadListView [items]="myItems" heigh="400">
                <ng-template tkListItemTemplate let-item="item" let-i="index" let-odd="odd" let-even="even">
                    <StackLayout  orientation="vertical">
                        <Label [text]='"index: " + i'></Label>
                        <Label [text]='"[" + item.id +"] " + item.name'></Label>
                    </StackLayout>
                </ng-template>
            </RadListView>
        </GridLayout>
    </StackLayout>
    <StackLayout tkMainContent>
        <Label text="Main page" textWrap="true" class="drawerContentText"></Label>
    </StackLayout>
</RadSideDrawer>
</GridLayout>

items.component.ts

import { Component, ElementRef, ViewChild, Injectable, AfterViewInit, OnInit, ChangeDetectorRef } from "@angular/core";


class DataItem{
    constructor(public id:number, public name:string){}
}

import { Item } from "./item";
import { ItemService } from "./item.service";

@Component({
    selector: "ns-items",
    moduleId: module.id,
    templateUrl: "./items.component.html",
})
export class ItemsComponent{
    public myItems: Array<DataItem>;
    private counter: number;

    constructor() {
        this.myItems = [];
        this.counter = 0;
        for (var i = 0; i < 50; i++) {
            this.myItems.push(new DataItem(i, "data item " + i));
            this.counter = i;
        }
    }
}
person Nikolay Tsonev    schedule 12.09.2016
comment
Этот код устарел, @nikolay-tsonev можете обновить с помощью nativescript-angular/platform - person ishandutta2007; 30.05.2017
comment
привет @ishandutta2007, я внес необходимые изменения в пример, и теперь все должно работать как положено. - person Nikolay Tsonev; 30.05.2017