6

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?

1
  • Where are you putting the html element that is submitting the form? Commented Oct 30, 2017 at 23:26

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thinks, I did try your second option moments before posting this, declaring the q variable was the part I was missing. Thanks for your time and the straightforward explanation.
1

Some like this should work..

Maybe you want to read about model binding and forms.

html component

<form #searchValue='ngForm' class="some-css-class" (ngSubmit)='submitSearch()'>
  <div>
    <input type="text" name="q" [(ngModel)]="searchValue" placeholder="search">
    <input type="submit" name="btn" placeholder="Submit">
  </div>
</form>

In component.ts

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 {

  searchValue: string = '';

  constructor() { }

  ngOnInit() { }

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.