代码之家  ›  专栏  ›  技术社区  ›  blackHawk

Ionic2:输入字段,为什么我的值为空字符串

  •  1
  • blackHawk  · 技术社区  · 8 年前

    这是我的客户端:

    <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 在…内 addcomment()

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

    this.comment ( AbstractControl 类内变量的类型)为空。

    3 回复  |  直到 8 年前
        1
  •  1
  •   Thierry Templier    8 年前

    如果要将控件与输入关联,则需要使用 NgFormControl 指令:

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

    不要把它放进 comment 绑定的属性 ngModel .

    编辑

    您还需要通过以下方式在表单标记上设置表单:

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

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

        2
  •  0
  •   Günter Zöchbauer    8 年前

    这仅更新 comment 从输入字段

    (ngModel) = 'comment'>
    

    但是如果 议论 变化。

    改用双向绑定

        [(ngModel)] = 'comment'>
    

    此外,您不希望将控件用作模型。模型是您想要保持价值的地方,因此它应该类似于

        [(ngModel)] = 'commentValue'>
    
        3
  •  0
  •   Guillaume    8 年前

    以下是我在项目中所做的:

    • 在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>
    

    请注意 #ngForm 以及 addComment(myForm) 在表单标记上。 请注意 [(ngModel)] 以及 required 在输入标签上。 我还在“添加注释”上添加了验证 button .

    • 在.ts:
    constructor()  {
        this.model = {
            comment: ""
        };
    }
    
    onLogin(form) {
        if (form.valid) {
            console.log(this.model);
        }
    }