I have interface as follow in Ionic :
// mydata.model.ts
export interface Mydata{
id: string;
name: string;
date: string
}
I'd like to add a new data to the backend so i'm binding my data within my component inside the <ion-input>
as follow :
// add-data.page.ts
import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
import { Mydata } from '../home/mydata.model';
@Component({
selector: 'app-add-data',
templateUrl: './add-data.page.html',
styleUrls: ['./add-data.page.scss'],
})
export class AddDataPage implements OnInit {
thedata: Mydata;
constructor(private dk: DataService) { }
ngOnInit(){
}
showData(){
console.log(this.thedata);
}
}
And here is my add-data components :
<ion-content>
<ion-item>
<ion-label position="floating">Name</ion-label>
<ion-input [(ngModel)]="thedata.name" name="myname"></ion-input>
</ion-item>
<ion-item>
<ion-label position="floating">Date</ion-label>
<ion-input [(ngModel)]="thedata.date" name="mydate"></ion-input>
</ion-item>
<ion-button padding expand="full" size="medium" (click)="showData()">
<ion-icon name="add-circle" slot="start"></ion-icon> Add Data
</ion-button>
</ion-content>
My question is why did the data binding not working in this situation?
I mean I cannot print the data in console.
I got an error message:
ERROR TypeError: Cannot read property 'name' of undefined.
I could however print the data in console if I changed the value of [(ngModel)]
with string type data. So to make my question more clear, what is the correct way of binding input data with interface in Angular?
You need to initialize the interface to be able to bind it in the template, example:
thedata : Mydata =
{
id : "1",
name : "john",
date : "01/02/2019"
}
Then you can do (ngModel)]="thedata.name"