I have using material dialogs for Angular, where I need to enter title and select approve or reject variant.
Here code of the component
import {Component, Inject, OnInit} from '@angular/core';
import {MAT_DIALOG_DATA, MatDialogRef} from "@angular/material";
import {FormBuilder, Validators, FormGroup} from "@angular/forms";
import { Payment } from '../payments/payment';
@Component({
selector: 'editing-dialog',
templateUrl: './editing-dialog.component.html',
styleUrls: ['./editing-dialog.component.scss']
})
export class EditingDialogComponent implements OnInit {
form: FormGroup;
reason:String;
id: Number;
statusdescription: String;
constructor(
fb: FormBuilder,
private dialogRef: MatDialogRef<EditingDialogComponent>,
@Inject(MAT_DIALOG_DATA) data:Payment) {
this.reason = data.Reason;
this.id = data.Id;
this.statusdescription = data.StatusDescription;
this.form = fb.group({
reason: [this.reason, Validators.maxLength(5)],
id: this.id,
status: status
});
}
ngOnInit() {
}
save() {
this.dialogRef.close(this.form.value);
}
close() {
this.dialogRef.close();
}
}
And here is html of this component
<h2>{{description}}</h2>
<mat-dialog-content [formGroup]="form">
<mat-form-field>
<input matInput required placeholder="Payment Reason" formControlName="reason" value="{{reason}}">
</mat-form-field>
<mat-radio-group formControlName="status">
<mat-radio-button value="Approved">Approved</mat-radio-button>
<mat-radio-button value="Rejected">Rejected</mat-radio-button>
</mat-radio-group>
</mat-dialog-content>
<mat-dialog-actions>
<button class="mat-raised-button" (click)="save()">
Ok
</button>
<button class="mat-raised-button"
(click)="close()">
Close
</button>
</mat-dialog-actions>
I need to make validation if input is filled and if one of radio buttons selected when I click ok button. Now I have required validation for input.
How I can do this corretly?
Thanks for help.
when you create the form group, add required rule to fields you want to be required, for example here reason and status fields are required:
this.form = fb.group({
reason: [this.reason, [Validators.required, Validators.maxLength(5)]],
id: this.id,
status: [status, [Validators.required]]
});
then in save method:
save() {
const {value, valid} = this.form;
if(valid){
this.dialogRef.close(value);
}
}
you may need to add mat-error element to show the validation errors in your html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With