3
votes

I am trying to just get some input from my Angular form. I want to see the input when I type. I get this error:

ContactFormComponent.html:6 ERROR TypeError: Cannot read property 'name' of undefined
    at Object.View_ContactFormComponent_0._co [as updateDirectives] (ContactFormComponent.html:6)
    at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:13067)
    at checkAndUpdateView (core.es5.js:12251)
    at callViewAction (core.es5.js:12599)
    at execComponentViewsAction (core.es5.js:12531)
    at checkAndUpdateView (core.es5.js:12257)
    at callViewAction (core.es5.js:12599)
    at execComponentViewsAction (core.es5.js:12531)
    at checkAndUpdateView (core.es5.js:12257)
    at callViewAction (core.es5.js:12599)

This is my form html template. I put ngModel in the form input where I'm trying to just type and see my input via the {{model.name}} binding.:

<div class="contact-wrap">

  <form #contactForm="ngForm" class="contact-form mx-auto">

    <label for="name">Name</label>
    <input type="text" id="name" [(ngModel)]="model.name" name="name"> {{model.name}}
    <label for="email">Email</label>
    <input type="text" id="email">
    <label for="message">Message</label>
    <textarea name="" id="message" cols="30" rows="4"></textarea >
    <input type="submit" class="contact-submit">

  </form>
</div>

This is my form component:

import { Component, OnInit } from '@angular/core';


@Component({
  selector: 'contact-form',
  templateUrl: './contact-form.component.html',
  styleUrls: ['./contact-form.component.scss']
})
export class ContactFormComponent implements OnInit {


  constructor() { }

  ngOnInit() {
  }


}

This is a part of my app.module.ts where I imported the FormsModule:

import { FormsModule } from '@angular/forms';
  imports: [
    BsDropdownModule.forRoot(),
    BrowserModule,
    CarouselModule.forRoot(),
    RouterModule.forRoot(appRoutes),
    BrowserAnimationsModule,
    Angulartics2Module.forRoot([Angulartics2GoogleAnalytics]),
    FormsModule
  ],

Also, here is the github repo if you'd like to see all the code.

1

1 Answers

2
votes

First of all

You can't assign undefined to the [(ngModel)]

<input type="text" id="name" [(ngModel)]="model.name" name="name"> {{model.name}} </input>

So you need to do it like :

<div *ngIf='model?.name'>
    <input type="text" id="name" [(ngModel)]="model.name" name="name"> {{model.name}} </input>
</div>

OR

From Component Side provide some initial values like :

// From your component
model = { 'name' : '' };

// then your code will work fine
<input type="text" id="name" [(ngModel)]="model.name" name="name"> {{model.name}} </input>