Как предотвратить отправку формы в отмененном Angular диалоге материалов? - PullRequest
0 голосов
/ 19 марта 2020

У меня есть Angular Диалог материала, который содержит форму, которая создает объект в моей внутренней базе данных Firestore.

У меня есть две кнопки в форме: одна вызывает отправку, другая отменяет, но даже когда я нажимаю кнопку отмены, запускается обработчик отмены, а затем запускается обработчик отправки, хотя я не вижу, как это было звонил.

В чем здесь проблема?

@Component({
  selector: 'app-create-budget',
  templateUrl: './create-budget.component.html',
  styleUrls: ['./create-budget.component.css']
})
export class CreateBudgetComponent implements OnInit {

  myForm: FormGroup;
  success=false;
  constructor(public dialogref: MatDialogRef<CreateBudgetComponent>, private fb : FormBuilder, private auth : AuthService, private budgetService: BudgetService ) { }

  ngOnInit(): void {
    this.myForm = this.fb.group( {
      name: ['',[Validators.required, Validators.minLength(2)]],
      revision: '1',
      masterCurrency: 'USD',
      owner: this.auth.userId,
      creationDate: Date.now(),
      description: ''
    })
    this.myForm.valueChanges.subscribe(console.log);
  }

  async submitHandler() {
    console.log("starting submit");
    const formValue : Budget = this.myForm.value;
    try {
      await this.budgetService.addNewBudget(formValue);
      this.dialogref.close();
    } catch(err) {
      console.error(err)
    }
  } 

  cancel() {
    console.log("Cancelled!");
    this.dialogref.close();
  }

  get name() {
    return this.myForm.get('name');
  }
  get masterCurrency() {
    return this.myForm.get('masterCurrency');
  }

}

Форма:

<h1 mat-dialog-title>Create New Budget</h1>
<div mat-dialog-content>
    <form [formGroup]="myForm" [hidden]="success" (ngSubmit)="submitHandler()">
        <mat-form-field>
            <input matInput placeholder="Budget Name" 
             formControlName="name">
             <mat-error *ngIf="name.invalid && name.touched">
                 A name (2 char min) is required. 
             </mat-error>
        </mat-form-field>  
        <mat-form-field>
            <input matInput placeholder="Revision" formControlName="revision">
        </mat-form-field>
        <mat-form-field>
            <textarea matInput placeholder="Description" 
            formControlName="description"></textarea> 
        </mat-form-field>
        <br>
        <button mat-raised-button color="primary" type="submit" [disabled]="myForm.invalid"  >Ok</button>
        <button mat-raised-button   (click)="cancel()">Never mind.</button>
    </form>
</div>

консольный вывод:

Cancelled!
create-budget.component.ts:38 starting submit
VM6:1 XHR finished loading: POST "https://firestore.googleapis.com/google.firestore.v1.Firestore/Write/channel?database=projects...

1 Ответ

1 голос
/ 19 марта 2020

попробуйте добавить type=button

...
<button (click)="cancel()" type="button">Never mind.</button>
...
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...