Ionic2:输入字段,为什么我在值中得到空字符串

Ionic2: Input field, Why Im getting empty string in value

这是我的客户端:

<ion-card *ngFor="#p of posts | async">
    <ion-card-header>
        {{p.title}}
    </ion-card-header>

    <ion-card-content>
        <form [ngFormModel] = 'form' (ngSubmit) = 'addcomment(form.value, p.$key)'>
            <ion-input  type="text" placeholder="your comment" (ngModel) = 'comment'></ion-input>
            <button>add comment</button>
        </form>
    </ion-card-content>
</ion-card>

在 .ts 中:

this.form = fb.group({
    'comment': ['', Validators.required]
});
this.comment = this.form.controls['comment']

如果我在控制台中打印 form.value inside addcomment()

Control {asyncValidator: null, _pristine: true, _touched: false, _value: "", _errors: Object…}

this.commentAbstractControl里面的变量类型class)为空。

这只会从输入字段

更新 comment
(ngModel) = 'comment'>

但如果 comment 更改,输入字段不会更新。

改用双向绑定

    [(ngModel)] = 'comment'>

您也不想将控件用作模型。该模型是您要维护价值的地方,因此它应该类似于

    [(ngModel)] = 'commentValue'>

如果您想将控件与您的输入相关联,您需要使用 NgFormControl 指令:

<ion-input type="text" placeholder="your comment" 
           [(ngModel)] = "comment"
           [ngFormControl]="this.form.controls['comment']">
</ion-input>

不要将它设置到 comment 属性 你绑定 ngModel.

编辑

您还需要以这种方式在表单标签上设置您的表单:

<form [ngFormModel]="form">
  (...)
</form>

有关详细信息,请参阅本文:

这是我在我的项目中所做的:

  • 在HTML中:
<form #myForm="ngForm" (ngSubmit)='addComment(myForm)'>
    <ion-input type="text" placeholder="your comment" [(ngModel)]='model.comment' #comment="ngForm" required></ion-input>
    <button [disabled]="!myForm.form.valid">add comment</button>
</form>

注意表单标签上的 #ngFormaddComment(myForm)。 请注意输入标签上的 [(ngModel)]required。 我还在 "Add Comment" button.

上添加了验证
  • 在 .ts 中:
constructor()  {
    this.model = {
        comment: ""
    };
}

onLogin(form) {
    if (form.valid) {
        console.log(this.model);
    }
}