[英]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.