我在Angular中使用了材质对话框,我需要在其中输入标题并选择批准或拒绝变体。
此处的组件代码
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();
}
}
这是此组件的html
<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>
如果输入被填充,并且单击ok
按钮时选择了单选按钮之一,则需要进行验证。现在,我需要输入验证。
我该如何正确地做到这一点?
感谢帮助。
创建表单组时,将所需的规则添加到想要的字段中,例如,此处的原因和状态字段是必需的:
this.form = fb.group({
reason: [this.reason, [Validators.required, Validators.maxLength(5)]],
id: this.id,
status: [status, [Validators.required]]
});
然后在保存方法中:
save() {
const {value, valid} = this.form;
if(valid){
this.dialogRef.close(value);
}
}
您可能需要添加mat-error元素以在html中显示验证错误
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句