Home > database >  How to put more than one parameter in the ngSubmit fonction in angular?
How to put more than one parameter in the ngSubmit fonction in angular?

Time:07-25

I'm trying to display data from my customer table using 3 search parameters (last name,first name,phone). The results are not conclusive and I wonder if my way is correct... Do you have a solution for me?

client.component.ts : client.component.ts

client.component.html: client.component.html

client.service.ts: client.service.ts

Result:

Result incorrect

CodePudding user response:

By looking at the error screenshot it seems like it was not able to pass the f.value object. Button to create a new Client is outside the form element. I believe you're just calling the onSearch2 function.

<div>
  <form #f="ngForm" (ngSubmit)="onSearch2(f.value)">
    <label>
      Name
      <input ngModel name="name" />
    </label>
    <label>
      Age
      <input ngModel name="age" />
    </label>
  </form>
</div>
<button type="button" (click)="form.ngSubmit.emit()">Submit</button>

Call ViewChild on form of type NgForm.

@ViewChild('f') form: NgForm;

And then call f.ngSubmit.emit() to trigger the ngSubmit event on form.

Stackblitz

CodePudding user response:

f.value does not contain any value. f is just a reference to ngForm which does not actually hold the input's values. I would recommend refactoring your form controls (inputs) to two-way bind to an object named personData, this will also give you easy access to form values later on. onSearch2() read values from object personData. If this works for you add types instead of any afterwards.

Other way to keep this entirely in template you would need to make unique template references using # on each individual input and pass reference values to onSearch2() (much the way you are doing right now, but instead of referencing f three times, you reference each individual input.

In html refactor ngSubmit and refactor input's.

(ngSubmit)="onSearch2()"

[(ngModel)]="personData.firstName"
[(ngModel)]="personData.lastName"
[(ngModel)]="personData.phone"

Ts:

  personData: any = {};

  onSearch2() {
    this.clientService.searchClientUnique(personData.firstName, 
               personData.lastName, personData.phone).subscribe(data => {
    console.log(data)  
     });
  }

See an example of a template driven form: https://stackblitz.com/edit/angular-6-template-driven-form-validation-z1gcbn?file=app/app.component.html

  • Related