[英]How to create validated form in angular material dialog
我有材质对话框,想在里面实现表单验证。 如果我创建这样的表单:
<form [formGroup]="qmForm" (ngSubmit)="submit(qmForm)">
<h2 mat-dialog-title>Add new Qmanager</h2>
<mat-dialog-content class="mat-typography">.....</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button type="button" mat-dialog-close>Cancel</button>
<button mat-raised-button color="primary" [disabled]="!qmForm.valid" type="submit">Add</button>
</mat-dialog-actions>
</form>
我收到错误 - not allowed to load local resource, and blank page
。
如果我让它像:
<mat-dialog-content class="mat-typography" [formGroup]="qmForm">
<mat-form-field>
<input matInput class="form-control" placeholder="Name" required formControlName="name" name='name'>
<mat-error *ngIf="name.invalid">
<div *ngIf="name.errors.required">
Name is required.
</div>
</mat-error>
</mat-form-field>
<br>
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button mat-dialog-close>Cancel</button>
<button mat-raised-button color="primary" [disabled]="!qmForm.valid" type="submit">Add</button>
</mat-dialog-actions>
没有验证并得到错误 - ERROR TypeError: Cannot read property 'invalid' of undefined
在app.module.ts
我导入了表单模块:
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
in app.components.ts - also:
import { ReactiveFormsModule, FormControl, FormGroup, Validators, FormBuilder, NgForm} from '@angular/forms';
export class...{
public qmForm: FormGroup;
constructor(private formBuilder: FormBuilder..)
ngOnInit () {
this.qmForm = new FormGroup({
name: new FormControl('', [Validators.required, Validators.minLength(4), Validators.maxLength(60)]),
hostname: new FormControl('', [Validators.required, Validators.minLength(4), Validators.maxLength(60)])
}, { updateOn: 'blur' });
);
createQM(qmForm) {
if(this.qmForm.valid) {
alert("test");
window.electronIpcSend('addQM', qmForm);
this.qmForm.reset();
}
}
如果你能帮助我理解我所缺少的。
谢谢!
编辑:
要获得有效的控制状态,请尝试像这样使用
<mat-error *ngIf="qmForm.controls.name.hasError('minlength')">Min length must be 6</mat-error>
并如上面的示例将其用于另一个控件
编辑:尝试使用?
<mat-error *ngIf="qmForm?.controls?.name?.hasError('minlength')">Min length must be 6</mat-error>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.