OleTuck
OleTuck

Reputation: 21

ERROR TypeError: Cannot read property 'city' of undefined

My problem is that when I run my application/web page, I am getting the error

ERROR TypeError: Cannot read property 'city' of undefined.

Here is my code, and it is pretty simple. (just learning angular btw)

import { Places } from '../models/places';

@Component({
  selector: 'app-place-form',
  templateUrl: './place-form.component.html',
  styleUrls: ['./place-form.component.css']
})
export class PlaceFormComponent implements OnInit {
  model: Places = new Places();

  constructor() { }

  ngOnInit() {

  }

  formSubmit(){
    console.log('Submit successful..', this.model);
  }
}

here is my HTML

<form (ngSubmit)='formSubmit()'>
  <div>
    <label for="city">City:</label>
    <input placeholder="city" id="city" name="city" [(ngModel)]="places.city" required />
  </div>
  <div>
    <label for="country">Country: </label>
    <input placeholder="country" id="country" name="country" [(ngModel)]="places.country" required />
  </div>
  <div>
    <label for="description">Description: </label>
    <textarea placeholder="description" id="description" name="description" [(ngModel)]="places.description" required></textarea>
  </div>
  <div>
    <button type="submit">Submit</button>
  </div>
</form>

and here is my model

export class Places {
    id: number;
    city: string;
    country: string;
    description: string;
}

I have tried using the safe navigation operator (?), but it throws a different error when I do that and breaks the whole page.
I am pretty sure I have everything imported correctly.
I know this is going to be a simple fix, I just don't really know what else to try.

Any help is appreciated and if you need more code or anything to help answer please let me know. Thanks again for your help!

Upvotes: 0

Views: 533

Answers (1)

The places is not defined any where in the component.ts you shared. And you trying to take [(ngModel)]="places.city" in HTML. Here instead of [(ngModel)]="places.city", you should use [(ngModel)]="model.city". I think the below snippet should work:

<form (ngSubmit)='formSubmit()'>
  <div>
    <label for="city">City:</label>
    <input placeholder="city" id="city" name="city" [(ngModel)]="model.city" required />
  </div>
  <div>
    <label for="country">Country: </label>
    <input placeholder="country" id="country" name="country" [(ngModel)]="model?.country" required />
  </div>
  <div>
    <label for="description">Description: </label>
    <textarea placeholder="description" id="description" name="description" [(ngModel)]="model.description" required></textarea>
  </div>
  <div>
    <button type="submit">Submit</button>
  </div>
</form>

Hope this helps.

Upvotes: 2

Related Questions