首页 > 解决方案 > NativeScript:未呈现的简单模板

问题描述

通过 *ngFor 调用模板时,无论多么简单,它都不会被渲染。

组件.html:

<Label text="hello world""></Label>

容器.html:

<StackLayout>
    <GridLayout *ngFor="let obj of objs">
        <!-- WORKS: -->
        <Label text="hello world"></Label>
        <!-- DOES NOT WORK: -->
        <ns-component></ns-component>
    </GridLayout>
</StackLayout>

当使用 , 下的代码段(简单的非模板标签)时,对于 3 个对象的数组,我看到三行“hello world”。但是,当调用模板而不是简单的 Label 时,不会呈现任何内容。

标签: nativescriptangular2-nativescript

解决方案


确保您已经在相应的模块中注册了您的组件。

例如

使用选择器创建组件ns-component

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

@Component({
    selector: "ns-component",
    moduleId: module.id,
    template: '<Label text="ns-component: Some Content"></Label>',
    styleUrls: ['./item.component.css']
})
export class ItemComponent  { }

然后在加载的模块中注册组件

import { NgModule, NO_ERRORS_SCHEMA } from "@angular/core";
import { NativeScriptCommonModule } from "nativescript-angular/common";
import { NativeScriptFormsModule } from "nativescript-angular/forms";

import { HomeRoutingModule } from "./home-routing.module";
import { HomeComponent } from "./home.component";

import { ItemComponent } from "./item.component"; // HERE

@NgModule({
    imports: [
        NativeScriptCommonModule,
        HomeRoutingModule,
        NativeScriptFormsModule
    ],
    declarations: [
        HomeComponent,
        ItemComponent // HERE
    ],
    schemas: [
        NO_ERRORS_SCHEMA
    ]
})
export class HomeModule { }

最后根据需要使用*ngFor结构指令。

<StackLayout>
    <GridLayout rows="100" *ngFor="let obj of [1, 2, 3, 4]" class="cell">
        <ns-component></ns-component>
    </GridLayout>
</StackLayout>

Playground 应用程序在此处演示上述内容。


推荐阅读