我在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
按钮时选择了单选按钮之一,则需要进行验证。现在,我需要输入验证。
我该如何正确地做到这一点?
感谢帮助。
答案 0 :(得分:1)
创建表单组时,将所需的规则添加到想要的字段中,例如,此处的原因和状态字段是必填项:
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中显示验证错误
答案 1 :(得分:0)
正在构建表单时
this.form = fb.group({
reason: [this.reason, [Validators.required, Validators.maxLength(5)]],
id: this.id,
status: status
});
保存时
save() {
if(this.form.valid) {
this.dialogRef.close(this.form.value);
}
}
答案 2 :(得分:0)
首先确认我是否正确理解了您的问题。您必须单击“确定”按钮并获得表单的验证。 如果这是问题,那么这里是解决方案: 在.ts中定义表单组:
this.form = fb.group({
reason: [this.reason, Validators.compose([Validators.required, Validators.maxLength(5)])],
id: this.id,
status: status
});
请定义状态的默认值,因为在上面的代码片段中看不到状态的定义。
现在点击确定按钮调用功能
clickOK(): void {
if (this.form.valid) {
console.log('form is valid')
} else {
console.log('form is invalid')
}
}
如果两个formcontrol验证都为true,则this.form.valid将返回true。如果任何一个失败,则它将返回false。