简体   繁体   中英

How to submit a template driven angular form without any submit button?

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 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.

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');
        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM