Angular form input value undefined
Asked Answered
P

2

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?

Pummel answered 30/10, 2017 at 22:57 Comment(1)
Where are you putting the html element that is submitting the form?Electroscope
M
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.

Myers answered 30/10, 2017 at 23:27 Comment(1)
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.Pummel
E
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);
  }
}
Electroscope answered 30/10, 2017 at 23:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.