Clear form without sending it [closed]

-1

I am working with Angular 5 and I have a form with different validations. When touching a field the error appears, but if I leave the form without sending it and I re-enter, the form continues with the fields in red. Does anyone know how to clean the form?

    
asked by Luisa Fernanda 19.01.2018 в 13:17
source

1 answer

-1

I do not know how you put the placeholders, but using the following component, when you press the Clear button (you execute the clear() method, which simply makes a reset() of the form object) they are deleted all fields and placeholders are maintained. Here you can see the demo:

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { User } from './signup.interface';

@Component({
  selector: 'signup-form',
  template: '
    <form novalidate (ngSubmit)="onSubmit(user)" [formGroup]="user">
      <label>
        <span>Full name</span>
        <input type="text" placeholder="Your full name" formControlName="name">
      </label>
      <div class="error" *ngIf="user.get('name').touched && user.get('name').hasError('required')">
        Name is required
      </div>
      <div class="error" *ngIf="user.get('name').touched && user.get('name').hasError('minlength')">
        Minimum of 2 characters
      </div>
      <div formGroupName="account">
        <label>
          <span>Email address</span>
          <input type="email" placeholder="Your email address" formControlName="email">
        </label>
        <div
          class="error"
          *ngIf="user.get('account').get('email').hasError('required') && user.get('account').get('email').touched">
          Email is required
        </div>
        <label>
          <span>Confirm address</span>
          <input type="email" placeholder="Confirm your email address" formControlName="confirm">
        </label>
        <div
          class="error"
          *ngIf="user.get('account').get('confirm').hasError('required') && user.get('account').get('confirm').touched">
          Confirming email is required
        </div>
      </div>
      <button type="submit" [disabled]="user.invalid">Sign up</button>
      <button type="button" (click)="clear()">Clear</button>
    </form>
  '
})
export class SignupFormComponent implements OnInit {
  user: FormGroup;
  constructor() {}
  ngOnInit() {
    this.user = new FormGroup({
      name: new FormControl('', [Validators.required, Validators.minLength(2)]),
      account: new FormGroup({
        email: new FormControl('', Validators.required),
        confirm: new FormControl('', Validators.required)
      })
    });
  }
  onSubmit({ value, valid }: { value: User, valid: boolean }) {
    console.log(value, valid);
  }
  clear() {
    console.log("clear clicked")
    this.user.reset();
  }
}
    
answered by 19.01.2018 / 16:05
source