【问题标题】:NativeScript TextField [(ngModel)] does not workNativeScript TextField [(ngModel)] 不起作用
【发布时间】:2018-02-25 11:46:46
【问题描述】:

我在 TextField 中通过 ngModel 绑定数据时遇到问题

我有模型课

export class Product {
    name: string
    description: string
    imageUrl: string
}

查看:

<GridLayout backgroundColor="red">
    <!--
    This part is for logged users
    -->
    <StackLayout
        [id]="container"
        [visibility]="isLogged ? 'visible' : 'collapse'">
            <Label text="Add product" textWrap="true"></Label>
            <TextField
                hint="product name"
                [(ngModel)]="product.name">
            </TextField>
            <TextField
                hint="product desc"
                [(ngModel)]="product.description">
            </TextField>
            <Button text="Zrób zdjęcie produktu" (tap)="didTapTakePhoto()">
            </Button>
            <Button text="Wyślij na serwer" (tap)="didTapSendProduct()">
            </Button>
            <Image #photo></Image>
    </StackLayout>

    <!--
    This part is for not logged users
    -->
    <StackLayout [visibility]="isLogged ? 'collapse' : 'visible'">
        <Label text="Musisz się zalogować!" textWrap="true"></Label>
    </StackLayout>

</GridLayout>

和控制器:

import { Component, OnInit, OnDestroy, ViewChild, ElementRef } from "@angular/core"
import * as Firebase from "nativescript-plugin-firebase"
import * as camera from "nativescript-camera";
import { Image } from "ui/image";
import { ImageAsset } from "image-asset"
import { ImageSource } from "image-source"
import { Product } from "../../shared"

@Component({
    selector: "AddProductComponent",
    templateUrl: "tabs/addProduct/addProduct.html"
})
export class AddProductComponent implements OnInit, OnDestroy {

    @ViewChild("photo") photoRef: ElementRef
    filePath: string
    isLogged: boolean = true

    product: Product

    listener = {
        onAuthStateChanged: function(data) {
            this.isLogged = data.loggedIn
        },
        thisArg: this
    }

    constructor() {
        this.product = new Product()
        this.product.name = "Name"
        this.product.description = "Desc"
    }

    ngOnInit(): void {
        Firebase.addAuthStateListener(this.listener)
        camera.requestPermissions()
    }

    ngOnDestroy(): void {
        Firebase.removeAuthStateListener(this.listener)
    }

    didTapTakePhoto() {
        // init the file-system module
        var fs = require("file-system");
        // grab a reference to the app folder
        var appPath = fs.knownFolders.currentApp().path;
        // determine the path to a file in the app/res folder
        this.filePath = appPath + "/cached_product_photo.png";

        camera.takePicture()
            .then((imageAsset) => {
                let photo = <Image>this.photoRef.nativeElement
                photo.src = imageAsset
                let photoSrc = new ImageSource()
                photoSrc.fromAsset(imageAsset).then(image => {
                    console.log("Result: " + image)
                    image.saveToFile(this.filePath, "png")
                })
            })
            .catch((err) => {
                console.log("Error -> " + err.message)
            });
    }

    didTapSendProduct() {
        console.log(this.product.name)
        console.log(this.product.description)
    }

    focusDescription() {
        console.log(this.product.name)
    }

    //TODO: move to separate file/import some more professional uuid generator?/
    // find any other way to distinguish betweeen photos
    getUUID() {
        function s4() {
            return Math.floor((1 + Math.random()) * 0x10000)
                .toString(16)
                .substring(1)
        }
        return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4()
            + s4() + s4()
    }
}

当我在 iOS 设备上运行我的应用程序时

  • 文本字段为空(这不应该是因为我在 constructor() 中的实现)
  • 当我点击发送按钮时,didTapSendProduct() 会打印一个函数:

    CONSOLE LOG file:///app/tabs/addProduct/addProduct.component.js:51:20: Name

    CONSOLE LOG file:///app/tabs/addProduct/addProduct.component.js:52:20: Desc

    无论文本字段中设置什么

请注意,我在导入中设置了 NativeScriptFormsModule

import { NgModule, NgModuleFactoryLoader } from "@angular/core";
import { NativeScriptFormsModule } from "nativescript-angular/forms";
import { NativeScriptModule } from "nativescript-angular/nativescript.module";
import { NSModuleFactoryLoader } from "nativescript-angular/router";

import { AppComponent } from "./app.component";
import { AppRoutingModule } from "./app-routing.module";

@NgModule({
    bootstrap: [
        AppComponent
    ],
    imports: [
        NativeScriptModule,
        AppRoutingModule,
        NativeScriptFormsModule
    ],
    declarations: [
        AppComponent
    ],
    providers: [
        { provide: NgModuleFactoryLoader, useClass: NSModuleFactoryLoader }
    ]
})
export class AppModule { }

【问题讨论】:

  • 除了 AppModule 之外,您还有其他模块吗?如果您的组件属于另一个模块,请确保将 NativeScriptFormsModule 导入该模块!

标签: ios typescript nativescript


【解决方案1】:

确保在声明 AddProductComponent 组件的模块上导入 NativeScriptFormsModule,而不仅仅是在 AppModule 中。

例子:

componentName.module.ts

import { NativeScriptCommonModule, NativeScriptFormsModule } from "nativescript-angular";
import { ComponentName } from "./componentName.component";

@NgModule({
  imports: [
    NativeScriptFormsModule
  ],
  declarations: [
    ComponentName
  ],
  schemas: [
    NO_ERRORS_SCHEMA
  ]
})
export class ComponentModule { }

【讨论】:

  • 不客气。你不是第一个问这个问题的人!我花了几个小时来找出为什么两种方式的数据绑定不起作用!
  • 你能推荐一个好的资源来阅读ModulesComponents的概念吗?博客还是书籍?
  • 您可以从官方网站angular.io/guide/architecture 和nativescript ng-tutorial docs.nativescript.org/tutorial/ng-chapter-0 阅读有关角度的基础知识
  • 我已调整此答案以包含示例并修复语法错误。
【解决方案2】:

你可以这样做

查看

<TextField [(ngModel)]="your_binding"></TextField>

模块

import { NativeScriptCommonModule, NativeScriptFormsModule } from '@nativescript/angular';
import { YourComponent } from "../foo"
@NgModule({
  imports: [
    NativeScriptCommonModule,
    NativeScriptFormsModule
 ],
  exports: [],
  declarations: [
     YourComponent
  ],
  providers: [],
  schemas: [
    NO_ERRORS_SCHEMA
  ]
})

它对我有用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多