Search code examples
formsangulartypescriptangular4-forms

Angular form input value undefined


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?


Solution

  • 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.