0

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?

2
  • it should be thedata: Mydata; capital "M" Commented Mar 21, 2019 at 8:11
  • My bad. It's a typo. Still not working though. The error is still the same. Commented Mar 21, 2019 at 8:15

2 Answers 2

1

you need to initialize object to use keys or you can use class with constructor.

First way:

    // mydata.model.ts
export class Mydata{
   id: string;
   name: string;
   date: string
   constructor(){
      this.id = "";
      this.name = "";
      this.date = "";
   }
}

on your component.ts

theData: MyData = new MyData()

Second Way:

// mydata.model.ts
export interface Mydata{
   id: string;
   name: string;
   date: string
}

at your component.ts

theData: MyData = {id="", name: "", date: ""};
Sign up to request clarification or add additional context in comments.

Comments

0

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.