【发布时间】:2019-12-09 08:23:27
【问题描述】:
我正在使用角度步进器来显示我的所有数据并输入一些文本框,但我想在用户单击 Next 按钮时添加我的自定义验证。
stackblitz - material-stepper-custom-validation
html:
<mat-horizontal-stepper #stepper>
<mat-step>
<div class="m-10">
<input type="text" id="fname" placeholder="First Name" >
</div>
<div class="m-10">
<input type="text" id="lname" placeholder="Last Name" >
</div>
<div>
<button mat-button (click)="checkData()" matStepperNext>Next</button>
</div>
</mat-step>
<mat-step [stepControl]="secondFormGroup" [optional]="isOptional">
<button mat-button matStepperPrevious>Back</button>
<button mat-button matStepperNext>Next</button>
</mat-step>
<mat-step>
<ng-template matStepLabel>Done</ng-template>
You are now done.
<div>
<button mat-button matStepperPrevious>Back</button>
<button mat-button (click)="stepper.reset()">Reset</button>
</div>
</mat-step>
</mat-horizontal-stepper>
在这里,在进入下一步之前应该验证名字和姓氏,而不是使用 formGroup。
ts:
import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
@Component({
selector: 'stepper-optional-example',
templateUrl: 'stepper-optional-example.html',
styleUrls: ['stepper-optional-example.css']
})
export class StepperOptionalExample implements OnInit {
constructor() {}
ngOnInit() { }
checkData() {
let lname = (<HTMLInputElement>document.getElementById("fname")).value;
if(lname == '') {
alert('error');
}
return false;
}
}
怎么做? - 如果名字是空的,那么不要让他们去Next stepper。
【问题讨论】:
-
我建议你看看Reactive Forms。此外,这个
(<HTMLInputElement>document.getElementById("fname")).value在使用 Angular 时 100% 未完成。 -
如果没有反应形式,这可能吗?
-
@GiovaniVercauteren 另外我有一些典型的用户输入信息的看法。
-
@PathikVejani 您应该也可以使用模板驱动的表单来执行此操作,但代码不会那么干净。您应该能够通过将 [completed] 和 [editable] 指令添加到相应的 mat-step 元素中来防止进入下一步。
-
反应式方法有更多的选择,可以轻而易举地处理动态数据和动态表单元素,但它需要一些小的准备来设置,但最终你可以用反应式表单做更多的事情,但是如果您只是使用较小的设置,那么我建议使用下面发布的模板驱动方法。
标签: javascript angular validation angular-material angular-material-stepper