2

I am very new to Angular10 and have been told to do a task. Task Description:- I have to create a form that gets auto-submitted when all the fields are filled. But I am unable to do it, I am having difficulty on how I shall use the Resiter(regForm) function without any button clicks.

the app.component.html file

{{title}}

<div class="container text-center">
   <div class="row">
     <div class="form-bg">

      <form #regForm="ngForm" (ngSubmit)="Register(regForm)">
         <h2 class="text-center">Registration Form</h2>
         <br>

         <div class="form-group">
             <input type="text" class="form-control" placeholder="first Name" name="firstName" required ngModel>
         </div>
         <div class="form-group">
           <input type="text" class="form-control" placeholder="last Name" name="lastName" required ngModel>
         </div>
         <div class="form-group">
           <input type="email" class="form-control" placeholder="email" name="email"  required ngModel>
         </div>

         <br>
         <div class="align-center">
           <button type="submit" class="btn btn-primary" id="register">Register</button>
         </div>
         <ng-template *ngIf="regForm.valid ; then thenBlock">

         </ng-template>
         <ng-template #thenBlock>
           form is now valid

           <div (mousemove)="Register(regForm)"></div>
           <!-- {{Register(regForm)}} -->
           
         </ng-template>
      </form>
      
     </div>
   </div>
</div>

app.component.ts file is

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'TemplateDriven';


  Register(form : any){
    console.log(' button clicked ')
    console.log(form.controls.firstName.value);
    console.log(form.controls.lastName.value);
  }
}

How should I use the Register function? One more point, when I am using *ngIf, the function Register is getting called many number of times.

  • You can add on change event listener to parent and check after input change if all the field are completed and submit – Baruch Mashasha Aug 23 '20 at 10:25
  • This will submit form multiple time on change of each input. You should use `debounce` on each input tag and see if the value is modified in all fields, if it is not modified, the function should not be triggered. If all the input values are modified and after sometime the `register` function should be called. Note that, this is one of the worst case behaviours that a developer can use. Hope it helps!! – Anglesvar Aug 23 '20 at 11:21

2 Answers2

0

You can use angular reactive form to achieve it I have slightly updated your code so it looks something like.

app.component.html

<div class="container text-center">
 <div class="row">
  <div class="form-bg">

   <form [formGroup]="form">
     <h2 class="text-center">Registration Form</h2>
     <br>
     <div class="form-group">
         <input type="text" class="form-control" placeholder="first Name" formControlName="firstName">
     </div>
     <div class="form-group">
       <input type="text" class="form-control" placeholder="last Name" formControlName="lastName">
     </div>
     <div class="form-group">
       <input type="email" class="form-control" placeholder="email" formControlName="email">
     </div>

     <br>
     <div *ngIf="form.valid">
       form is now valid
        {{ formValue | json }}
       </div>
      </form>
  
   </div>
  </div>
</div>

app.component.ts

import { Component, VERSION, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

@Component({
 selector: 'my-app',
 templateUrl: './app.component.html',
 styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
form: FormGroup;
formValue: any;

constructor(private fb: FormBuilder) {}

register(){
  this.formValue = this.form.value
  console.log('form submitted now')
  console.log(this.formValue);
}

ngOnInit() {
  this.form = this.fb.group( {
    firstName: ['', Validators.required],
    lastName: ['', Validators.required],
    email: ['', Validators.required],
  })

 this.form.valueChanges.subscribe(() => {
    if (this.form.valid) {
      this.register()
    }
  })
 }
}

Here is the working DEMO hope this solve your problem.

Kamran Khatti
  • 3,754
  • 1
  • 20
  • 31
0

When considering automatic submissions, you need to consider few things

  • Make sure you submit only when required fields are filled in
  • Make sure you do not submit the form continuously when changes are occurring in the form fields and you resubmit only when there is any change

component.html

<form [formGroup]="form">
    <h2 class="text-center">Registration Form</h2>
    <br>
    <div class="form-group">
        <input type="text" class="form-control" placeholder="first Name" formControlName="firstName">
    </div>
    <div class="form-group">
        <input type="text" class="form-control" placeholder="last Name" formControlName="lastName">
    </div>
    <div class="form-group">
        <input type="email" class="form-control" placeholder="email" formControlName="email">
        <span *ngIf="form.controls['email']?.errors?.required">This field is required</span>
    </div>

    <br>
    <div *ngIf="form.valid">
        Valid form
    </div>
</form>

component.ts

ngOnInit() {
    this.form = this.fb.group({
        firstName: ['', Validators.required],
        lastName: [''],
        email: ['', Validators.required],
    });

    this.form.valueChanges.pipe(
        debounceTime(3000),
        distinctUntilChanged((a, b) => JSON.stringify(a) === JSON.stringify(b))
    ).subscribe(() => {
        if (this.form.valid) {
            console.log('Submit here');
        }
    });
}
Nipuna
  • 6,846
  • 9
  • 64
  • 87