我使用角步进显示我的所有数据,并接受一些文本框的输入,但我想添加我的自定义验证时,用户单击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步进。
发布于 2019-12-09 08:50:04
由于您使用模板驱动的方法,因此需要将所有输入字段以某种方式映射到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。
https://stackoverflow.com/questions/59244969
复制相似问题