#android #angular #typescript #nativescript
#Android #angular #typescript #nativescript
Вопрос:
Я следовал этому руководству, чтобы создать пользовательский компонент nativescript http://moduscreate.com/custom-components-in-nativescript / но у меня это не работает
У меня есть папка pages с папкой внутри, которая называется main. в главном есть несколько файлов
main.html
<StackLayout
xmlns="http://schemas.nativescript.org/tns.xsd"
xmlns:hello="pages/helllo"
loaded="pageLoaded" >
<hello:hello/>
</StackLayout>
main.component.ts
import { Component, ElementRef, OnInit, ViewChild} from "@angular/core";
import { Page } from "ui/page";
import colorModule = require("color");
var Color = colorModule.Color;
@Component({
selector: "my-app",
templateUrl: "pages/main/main.html",
styleUrls: ["pages/main/main-common.css"]
})
export class MainComponent implements OnInit{
constructor(private page: Page) {
}
ngOnInit() {
this.page.actionBarHidden = true;
}
}
и у меня также есть main-common.css, но это не важно показывать. Затем у меня есть еще одна папка внутри страниц с именем hello, в которой находится только один файл
hello.html
<StackLayout width="100%" height="100%" backgroundColorr="red">
<Label class ="h1" text="h1 hello world" color="black"></Label>
<Label class ="h1" text="h1 hello world" color="black"></Label>
<Label class ="h1" text="h1 hello world" color="black"></Label>
<Label class ="h1" text="h1 hello world" color="black"></Label>
<Label class ="h1" text="h1 hello world" color="black"></Label>
<Label class ="h1" text="h1 hello world" color="black"></Label>
<Label class ="h1" text="h1 hello world" color="black"></Label>
<Label class ="h1" text="h1 hello world" color="black"></Label>
<Label class ="h1" text="h1 hello world" color="black"></Label>
<Label class ="h1" text="h1 hello world" color="black"></Label>
<Label class ="h1" text="h1 hello world" color="black"></Label>
</StackLayout>
однако компонент hello не отображается независимо от того, что я делаю, я получаю только пустой экран. Я также попытался изменить эту строку xmlns:hello="pages/helllo"
в hello.html файл к этому xmlns:hello="../helllo"
, но я ничего не получил, даже ошибки. может кто-нибудь указать, что я делаю неправильно?
Комментарии:
1. Пользовательские компоненты работают только в vanilla NS в angular, вам нужно это как angular shared, не уверен, что это называется, поскольку я не использую angular
2. что лучше использовать vanilla NS или angular?
3. У каждого есть свои плюсы и минусы, я использую vanilla, поскольку у меня была такая же проблема и многое другое, что приводило к ошибкам, когда я начинал с NS, но ng2 лучше, если вы знакомы с ним или вам нужно будет повторно использовать логику для веб-сайта
Ответ №1:
То, что вы имеете в виду, действительно в ядре NativeScript, но не будет работать в NativeScript Angular-2.
Вместо этого вам нужно создать пользовательский компонент способом Angular-2. Для демонстрации мы можем обратиться к этому образцу, в котором создается компонент пользовательского элемента. Пример также описан в документации, и он также покажет вам, как связать данные с помощью директивы @Input для этого компонента.
Позвольте мне провести вас через весь процесс.
1.) Создайте свой пользовательский компонент
использование-item-template.component.ts
import { Component, ChangeDetectionStrategy, Input } from "@angular/core";
@Component({
selector: 'item-component',
styleUrls: ["listview/using-item-template/using-item-template.component.css"],
template: `
<StackLayout *ngFor="let element of data.list" class="model">
<Label [text]="element.model" class="name"></Label>
<Label [text]="element.speed 'mph'" class="speed"></Label>
</StackLayout>
`
})
export class ItemComponent {
@Input() data: any; // this way we "pass data" to our item-component
}
@Component({
selector: 'using-item-template',
styleUrls: ["listview/using-item-template/using-item-template.component.css"],
templateUrl: "listview/using-item-template/using-item-template.component.html",
changeDetection: ChangeDetectionStrategy.OnPush
})
export class UsingItemTemplateComponent {
public manufacturers: Array<any>;
constructor() {
var bugatti = [{ "model": "Bugatti Chiron", "speed": "261" }, { "model": "Bugatti Veyron Super Sport", "speed": "268" }];
var mclaren = [{ "model": "McLaren P1", "speed": "211" }, { "model": "McLaren F1", "speed": "242" }];
var jaguar = [{ "model": "Jaguar XJ220", "speed": 217 }];
this.manufacturers = [{ "list": bugatti }, { "list": mclaren }, { "list": jaguar }];
}
}
using-item-template.component.html
<StackLayout exampleTitle toggleNavButton>
<GridLayout rows="50, *" class="example-container">
<Label text="Top Cars" row="0" class="title" textWrap="true" horizontalAlignment="center"></Label>
<ListView [items]="manufacturers" row="1">
<template let-item="item">
<item-component [data]="item" ></item-component>
</template>
</ListView>
</GridLayout>
</StackLayout>
Последняя, но также важная часть — не забудьте объявить свой ItemComponent в NgModule!
main.ts
import { ItemComponent } from "./listview/using-item-template/using-item-template.component";
@NgModule({
declarations: [
ItemComponent, // declare the item component
// the other components in your app
],
bootstrap: [AppComponent],
imports: [
.....
],
})
class AppComponentModule { }
Комментарии:
1. Большое вам спасибо, это работает отлично, но мне было интересно, что, если я захочу поместить ItemComponent в отдельный файл из using-item-template.component.ts?
2. Неважно, я это понял: D ответил и проголосовал за 🙂