Angular form input value undefined

Draxy picture Draxy · Oct 30, 2017 · Viewed 12.1k times · Source

I'm trying to get the value of an input field in my first ever Angular form, but it is always undefined, and I can't figure out why. I'm importing FormsModule correctly, and I can reference the form object fine, so I must be missing something obvious.

My components HTML

<form #searchValue='ngForm' class="" (ngSubmit)='submitSearch(searchValue)'>
  <div>
    <input type="text" name="q" placeholder="search">
  </div>
</form>

And my components ts method (Shortened)

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

@Component({
  selector: 'google-search',
  templateUrl: './google.component.html',
  styleUrls: ['./google.component.css']
})

export class GoogleComponent implements OnInit {

  constructor() { }

  ngOnInit() {

  }

  submitSearch(formData) {
    console.log(this.searching);
    console.log(formData.value.q);    
  }
}

Any ideas to why this is?

Answer

Martin Ad&#225;mek picture Martin Adámek · Oct 31, 2017

You need to mark the input with ngModel so angular will know that this is one of form's controls:

<input type="text" ngModel name="q" placeholder="search">

Or you can define the variable first in your component, and then bind the input to it via [(ngModel)] directive:

export class GoogleComponent implements OnInit {
  q: string;

  submitSearch() {
    console.log(this.q);
  }
}

<form class="" (ngSubmit)='submitSearch()'>
  <div>
    <input type="text" name="q" [(ngModel)]="q" placeholder="search">
  </div>
</form>

One way binding (just [ngModel]="q") could be enough if you just want to read the value from input.