使用nativescript 2 / angular 2,遇到数据绑定问题 . 我对angularJS 1.x很熟悉,但是我读到的文档,这应该是有效的 . 尝试了ngModel的不同变体,但没有工作 . record.name的值是“undefined” .
记录类只是定义了一个id和name字段 . 我的另一个问题是如何触发组件的更改事件?如果用户开始输入文本输入,如何在键入时调用组件中的函数?
下面是我的“html”:
<StackLayout>
<Textfield hint="Search for a Record" [(ngModel)]="record.name" (returnPress)="searchRecord()"></Textfield>
<Label text="{{ record.name }}"></Label>
<Button text="Search" class="btn" (tap)="searchRecord()"></Button>
<Button text="Take Photo" class="btn" (tap)="takePhoto()"></Button>
</StackLayout>
添加记录组件:
import {Component} from "@angular/core";
import cameraModule = require("camera");
import imageModule = require("ui/image");
import {Record} from "../../shared/record/record";
import {RecordService} from "../../shared/record/record-service";
@Component({
selector: "add-record",
templateUrl: "pages/add-record/add-record.html",
styleUrls: ["pages/add-record/add-record-common.css"],
providers: [ RecordService ]
})
export class AddRecordPage {
record: Record;
constructor(private _recordService: RecordService) {
this.record = new Record();
}
searchRecord() {
console.log(this.record.name + '!');
this._recordService.add(this.record)
.subscribe(
() => {
alert('a');
},
() => {
alert('b');
}
);
}
takePhoto() {
cameraModule.takePicture().then(picture => {
console.log("Result is an image source instance");
var image = new imageModule.Image();
image.imageSource = picture;
});
}
}
谢谢!
2 回答
我注意到"html"文件中绑定语法中的一些问题,这个问题不是用于NativeScript Angular-2的正确语法 . 检查我在类似主题上的答案here
比如你的:
应该成为:
您也可以查看关于data-binding in NativeScript + Angular-2的教程
转到应用程序的主模块,该模块由
platformNativeScriptDynamic().bootstrapModule()
加载 .[要查找主模块,请转到
main.ts
(或main.js
)文件(这是应用程序的入口点) . 找到如下所示的行:这里
AppModule
是第一个要加载的模块 .请参阅
import
语句以查找AppModule
定义在哪个文件中 . 它可能如下所示]
In the main module's file (app.component.ts) add two things ,
1)在顶部为
NativeScriptFormsModule
添加导入2)在主模块的
@NgModule
装饰器中,将NativeScriptFormsModule
添加到imports:
阵列,将其添加为导入的模块之一 .这个ngModel支持在1月27日之前没有出现 . 可以在this link找到
或者从nativescript.org教程中查看this exercise