Reputation: 7864
A User opens a Modal and shouldn't be able to Click Ok until he fills in the required input
I tried what is mentioned in documentation but doesn't work
Here is the working Demo stackblitz that needs to implement this
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>
Upvotes: 1
Views: 5264
Reputation: 2885
What about simply disable the ok button when the user doesn't fill any data ? Something like this :
<button mat-button [disabled]="!data.animal" [mat-dialog-close]="data.animal" cdkFocusInitial>Ok</button>
You can also wrap the input inside <form #form="ngForm">...</form>
tag and check if the form is valid [disabled]="form.invalid"
Upvotes: 4