Angular form does not take input value in input

0

I'm having a problem where angularity is not assigning value to the variable of an input field of mine.

Follow the code:

component.html

 <div class="row justify-content-center" id="formulario">
    <form class="form-inline" (submit)="findRegister(nameInput.value)">
      <input #nameInput type="text" class="form-control mb-2 mr-sm-2 mb-sm-0" placeholder="Jane Doe">
      <button type="submit" class="btn btn-primary">Pesquisar</button>
    </form>
  </div>

component.ts

import { Component, OnInit } from '@angular/core';
import { DataService } from '../services/data.service';
@Component({
  selector: 'app-table',
  templateUrl: './table.component.html',
  styleUrls: ['./table.component.css']
})
export class TableComponent implements OnInit {
  offset:number;
  registers:Register[];

  constructor(private dataService:DataService) { }

  findRegister(value){
    this.dataService.getRegisters(value, this.offset).subscribe(registers => {
      this.registers = registers.data;
      console.log(this.registers);
    }, err => {
      console.log(err);
    });
  }
  ngOnInit() {
    this.offset=1;
    this.findRegister("Luiz");
  }
  incrementOffset(){
    this.offset++;
    this.findRegister("luiz");
  }
  decrementOffset(){
    this.offset--;
    this.findRegister("luiz");
  }

}
interface Register{
  id: string,
  name: string,
  username: string;
}

I made some calls to findRegister passing a string just to test the service, which is working everything ok.

    
asked by anonymous 27.08.2017 / 17:56

1 answer

1

Try changing (submit) to (ngSubmit) .

<div class="row justify-content-center" id="formulario">
  <form class="form-inline" (ngSubmit)="findRegister(nameInput.value)">
    <input #nameInput type="text" class="form-control mb-2 mr-sm-2 mb-sm-0" placeholder="Jane Doe">
    <button type="submit" class="btn btn-primary">Pesquisar</button>
  </form>
</div>

UPDATE

I suggest you use Template-Driven Form because the changes will be minimal in your code.

You will need:

  • Import% with% of% with%
  • Create a template variable in its FormsModule and assign the value @angular/forms to it. Ex: <form>
  • Name your input using the ngForm attribute and put the <form #searchForm="ngForm"> directive on it. Ex: name
  • Then you pass by parameter to the submit ngModel method. Ex: <input type="text" name="name" ngModel />

Example:

<div class="row justify-content-center" id="formulario">
  <form class="form-inline" #searchForm="ngForm (ngSubmit)="findRegister(searchForm.value.name)">
    <input type="text" class="form-control mb-2 mr-sm-2 mb-sm-0" placeholder="Jane Doe" name="name" ngModel>
    <button type="submit" class="btn btn-primary">Pesquisar</button>
  </form>
</div>
    
28.08.2017 / 15:30