Home > Software engineering >  reset button click dosent work in custom angular reactive form
reset button click dosent work in custom angular reactive form

Time:12-27

Good morning all, I have a problem with the reset button which does not work for all fields with the custom form control, I use reactive form! attached an example:

Parent component TS


@Component({
  selector: 'parent',
  templateUrl: 'parent.component.html',
  styleUrls: ['parent.component.css'],
})
export class ParentComponent {



}

Parent Component HTML


<child-component > </chield-component>


Child Component TS

@Component({
  selector: 'child-component',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
 
 
  form: FormGroup;
 
  constructor(private fb: FormBuilder) {
  }
 
  countries = [
    { id: 1, name: "United States" },
    { id: 2, name: "Australia" },
    { id: 3, name: "Canada" },
    { id: 4, name: "Brazil" },
    { id: 5, name: "England" }
  ];
 
  ngOnInit() {
 
    this.form = this.fb.group({      
    country : [''],
    town : ['']
   });
 
  submit() {
    console.log(this.form.value)
  }
}


Child Component HTML



<form [formGroup]="form" (ngSubmit)="submit()">
 

 //this select have date from child component

  <select formControlName="country">
    <option *ngFor="let country of countries" [ngValue]="country.id">{{country.name}}</option>
  </select>

//this select have date from parent component

<select formControlName="town">
    <option *ngFor="let town of towns" [ngValue]="town.id">{{town.name}}</option>
  </select>


<button type="submit">Submit</button>
<button type="reset">Reset</button>

 
</form>


My question is houw can i reset all filed of this custom form knowing that one select have data from child component and one other form parant child !! it's very complicated for me ! Thank you all

I tried all the reset methods but it doesn't work.

CodePudding user response:

Angular Reactive Forms has a reset function which will do the job. And it's better you let do it Angular itself.

this.form.reset();

You can read more about it in the official docs.

Here is a Stackblitz example.

CodePudding user response:

Try this one

<button type="button" (click)="resetForm(form)">Reset</button>

resetForm = (form:FormGroup)=> {
 form.reset();
};
  • Related