How to reset only specific fields of form in angular 5

前端 未结 5 2273
名媛妹妹
名媛妹妹 2021-02-19 20:45

I have created a function in one of my component file that resets the form(myform):

`onSubmit() {
  if (this.myform.valid) {
    console.log(\"Form Submitted!\")         


        
相关标签:
5条回答
  • 2021-02-19 21:09

    try this:

    this.myform.controls['comments'].reset()
    
    0 讨论(0)
  • 2021-02-19 21:11

    In your html

    <select formControlName="idSala" (change)="clearField(1)">
     <option value="">Selecione uma sala</option>
    </select>
    

    <input type="text" formControlName="titulo">

    <input formControlName="dataHoraInicial" type="datetime-local">

    TS

    clearField(value) {
    if (value == 1) {
      this.formularioDeAgendamentoSala.controls['titulo'].reset();
      this.formularioDeAgendamentoSala.controls['dataHoraInicial'].reset();
    }
    

    }

    0 讨论(0)
  • 2021-02-19 21:21

    try this one:

      clearForm() {
        this.myForm.get('comments').reset();
        this.myForm.get('name').reset();
      }
    

    and call this function where you submit form.

    0 讨论(0)
  • 2021-02-19 21:26

    UPDATE:

    I just had this issue and although the accepted answer works, it has some tslint warnings. I ended up doing:

    this.myForm.get('formControlName').setValue(null);
    

    I'm working with Angular 8.

    And if you want to do it for several fields this works too:

    private controlNames = ['nameOne', 'nameTwo'];
    
    this.controlNames.map((value: string) => this.myForm.get(value).setValue(null));
    
    0 讨论(0)
  • 2021-02-19 21:28

    Yes you can access the controls using this.myform.controls get the control and call reset() on it

    0 讨论(0)
提交回复
热议问题