【问题标题】:[Angular2][NativeScript] template tag doesnt work in ListView[Angular2][NativeScript] 模板标签在 ListView 中不起作用
【发布时间】:2017-04-11 02:36:32
【问题描述】:

您好,我在使用 Angular2 的 NativeScript 中遇到了 ListView 的问题。

在我的指令中我有对象数组

export class Room {
constructor(
    public name: string,
    public tag: string
    ){ }
}

import { Page } from "ui/page";
import { Component, OnInit, EventEmitter, Output, ChangeDetectionStrategy } from '@angular/core';
import { NativeScriptRouterModule } from "nativescript-angular/router";
import { NativeScriptModule } from "nativescript-angular/nativescript.module";

@Component({
    moduleId: module.id,
    selector: 'rooms-list',
    templateUrl: "./template.html",
    providers: [RoomService],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class RoomsListComponent implements OnInit {

    public items: Array<Room> = [];

    listLoaded = false;

    load() {
        for (let i = 0; i < 200; i++) {
                this.items.push(
                    new Room("room " + i, "tag " + i)
                );

            }
    }
    ngOnInit(): void {
        this.load();
    }
    onTap(name){
        console.log('taped: '+name);
    }
}

在我的模板中我使用 ListView

<ListView [items]="items" id="roomsList">
    <template let-item="item">
        <StackLayout>
            <Label [text]='"[" + item.tag +"] " + item.name'></Label> 
        </StackLayout>
    </template>
</ListView>

但是看起来模板标签不存在,列表只包含 [object Object] 元素。

【问题讨论】:

  • 您的代码看起来不错?你用的是什么版本的 nativescript?
  • 是的,您使用的是什么版本,如果您使用的是 RC(意思是 Angular 4),&lt;template&gt; 已更改为 &lt;ng-template&gt;,此处类似问题:stackoverflow.com/a/43074761/3801632
  • @VladimirAmiorkov 与 ng-template 仍然无法正常工作。我使用的是 nativescript 2.5

标签: android angular listview nativescript


【解决方案1】:

@Component 中使用moduleId: module.id 时,您只需提供templateUrl 的名称,无需任何目录。使用 moduleId 可以在当前目录中查看任何 Url,因此您不再需要指定绝对路径。只需执行以下操作:

@Component({
    moduleId: module.id,
    selector: 'rooms-list',
    templateUrl: "template.html",
    providers: [ RoomService ],
    changeDetection: ChangeDetectionStrategy.OnPush
})

更多信息可以在this线程中找到,你也可以看看官方的NativeScript ng示例here

【讨论】:

  • 您能否尝试一个更简单的绑定表达式,例如[text]="item.tag",以确保 ListView 的项目实际已填充。您也可以编辑您的帖子以包含Room 对象的来源,也许那里有什么。
  • 我通过从我的 ngModule 中的 nativescript-angular/nativescript.module 导入 NativeScriptModule 来修复它。在此之前我在组件中导入它
【解决方案2】:

以下适用于 NativeScript/Angular 5,我认为也应该适用于 Angular 2。变化:

<StackLayout>

到:

<StackLayout (tap)="onTap(item)">

和:

onTap(name){
    console.log('taped: '+name);
}

到:

onTap(item){
    console.dir(item); // So item is a Room object
}

Angular 5 也需要 ng-template 而不是模板。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-20
    • 2016-10-02
    • 2011-04-28
    • 2016-03-22
    • 1970-01-01
    • 2021-03-07
    • 2013-04-02
    • 1970-01-01
    相关资源
    最近更新 更多