Search code examples
angularjsangularionic2ionic-viewangular2-forms

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


This is my client side :

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

And in .ts :

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

If i print in the console the form.value inside addcomment()

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

and this.comment (AbstractControl type of variable inside class) is empty.


Solution

  • If you want to associate a control with your input you need to use the NgFormControl directive:

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

    Don't set it into the comment property you bind with ngModel.

    Edit

    You also need to set your form on the form tag this way:

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

    See this article for more details: