Bishoy Ezzat Bishoy Ezzat - 1 year ago 159
TypeScript Question

cannot read property 'iname' of undefined angular4

I have this interface item.ts:-

export interface item{
$key?:string;
available?:boolean;
countable?:boolean;
iname?:string;
price?:string;
desc?:string;
image?:string;
}


The items component item.componenet.ts is :-

import { Component, OnInit } from '@angular/core';
//import { AdditemsService } from '../../services/additems.service';
import { item } from '../../item';

@Component({
selector: 'app-items',
templateUrl: './items.component.html',
styleUrls: ['./items.component.css']
})
export class ItemsComponent implements OnInit {

items:item={
$key :"",
available :true,
countable :true,
iname :"",
price :"",
desc :"",
image :""
};

constructor() { }

ngOnInit() {
}

}


and the html form item.componenet.html is :-

<form novalidate #fo="ngForm" (ngSubmit)="mySubmit(fo)">
<div class="form-group">
<label for="iname">Item Name : </label>
<input type="text" class="form-control" name="iname"
[(ngModel)]="item.iname" #iteminame="ngModel" required minlength="3">
</div>
<div *ngIf="iteminame.errors?.required && iteminame.touched"
class="alert alert-danger"></div>
<div *ngIf="iteminame.errors?.minlength &&
iteminame.touched" class="alert alert-
danger"></div>
<button type="submit" class="btn btn-
success">Submit</button>
</form>


the main problem that the ngModel can not see the iname that is created in the interface. I imported the interface in the component and after that I used ngModel to get make this textbox can add and validate on the textbox.

But I always see this error, cannot read property 'iname' of undefined.

I think the error is in this line.

<input type="text" class="form-control" name="iname" [(ngModel)]="item.iname" #iteminame="ngModel" required minlength="3">


any help ??

Answer Source

You have [(ngModel)]="item.iname" instead of [(ngModel)]="items.iname". Just a typo. There is no "item" property on your class, only "items".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download