使用角度材料步进器在输入类型文本中添加自定义验证



我正在使用角度步进器来显示我的所有数据并为某些文本框输入,但我想在用户单击按钮时添加我的自定义验证Next但我想添加我的自定义验证。

堆叠闪电战 - 材料步进定制验证

.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步进器。

由于您使用模板驱动的方法,因此需要以某种方式将所有输入字段映射到ngModel中。下面是一个示例:

.HTML:

<input type="text" required [(ngModel)]="model.name" name="name">

TS:

@Component({
selector: 'stepper-optional-example',
templateUrl: 'stepper-optional-example.html',
styleUrls: ['stepper-optional-example.css']
})
export class StepperOptionalExample implements OnInit {
@ViewChild('stepper') stepper;
model = {
name: 'Initial Value'
}
constructor() {}
ngOnInit() { }
}

然后,您可以使用它检查属性 onClick。您需要删除matStepperNext并添加(click)事件侦听器,如下所示:

.HTML:

<button mat-button (click)="onNext()">Next</button>

TS:

onNext() {
// Validate your value in the function
if (this.model.name !== 'Henry') {
this.stepper.next();
}
}

除此之外,我还建议查看官方指南,了解如何实现模板驱动方法:https://angular.io/guide/forms

相关内容

最新更新