Как сделать простую обязательную проверку в угловом модальном всплывающем окне? - PullRequest
0 голосов
/ 28 июня 2019

Пользователь открывает модал и не может нажимать кнопку ОК, пока не введет необходимые данные

Я пробовал то, что упомянуто в документации , но не работает

Вот рабочий демонстрационный стек * блик , который должен реализовать это

component.ts

import { Component, Inject } from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';

export interface DialogData {
  animal: string;
  name: string;
}

/**
 * @title Dialog Overview
 */
@Component({
  selector: 'dialog-overview-example',
  template: `<button mat-raised-button (click)="openDialog()">Pick one</button>
  <li *ngIf="animal">
    You chose: <i>{{animal}}</i>
  </li>`
})
export class DialogOverviewExample {

  animal: string;
  name: string;

  constructor(public dialog: MatDialog) { }

  openDialog(): void {
    const dialogRef = this.dialog.open(DialogOverviewExampleDialog, {
      width: '250px',
      data: { name: this.name, animal: this.animal }
    });

    dialogRef.afterClosed().subscribe(result => {
      console.log('The dialog was closed');
      this.animal = result;
    });
  }

}

@Component({
  selector: 'dialog-overview-example-dialog',
  templateUrl: 'dialog-overview-example-dialog.html',
})
export class DialogOverviewExampleDialog {

  constructor(
    public dialogRef: MatDialogRef<DialogOverviewExampleDialog>,
    @Inject(MAT_DIALOG_DATA) public data: DialogData) { }

  onNoClick(): void {
    this.dialogRef.close();
  }

}


/**  Copyright 2019 Google Inc. All Rights Reserved.
    Use of this source code is governed by an MIT-style license that
    can be found in the LICENSE file at http://angular.io/license */

dialog.html

<h1 mat-dialog-title>Hi {{data.name}}</h1>
<div mat-dialog-content>
  <p>What's your favorite animal?</p>
  <mat-form-field>
    <input required matInput name="myInput" [(ngModel)]="data.animal">
  </mat-form-field>
</div>
<div mat-dialog-actions>
  <button mat-button (click)="onNoClick()">No Thanks</button>
  <!-- <button mat-button [disabled]="myInput.errors.required" [mat-dialog-close]="data.animal" cdkFocusInitial>Ok</button> -->
     <button mat-button  [mat-dialog-close]="data.animal" cdkFocusInitial>Ok</button> 

</div>

1 Ответ

1 голос
/ 28 июня 2019

Как насчет просто отключить кнопку ОК, когда пользователь не заполняет данные?Примерно так:

<button mat-button [disabled]="!data.animal"  [mat-dialog-close]="data.animal" cdkFocusInitial>Ok</button>

Демонстрация Stackblick

Вы также можете обернуть ввод внутри тега <form #form="ngForm">...</form> и проверить, верна ли форма [disabled]="form.invalid"

...