angular 提交表单时,有错误提示,立即滚动到第一个错误提示的地方
this.userProfileForm.markAllAsTouched(); if (this.userProfileForm.controls.firstName.value == '') this.scrollToFirstInvalidControl('firstName'); else if (this.userProfileForm.controls.lastName.value == '') this.scrollToFirstInvalidControl('lastName'); else if (this.userProfileForm.controls.email.value == '') this.scrollToFirstInvalidControl('email'); else if (this.userProfileForm.controls.userLanguage.value == '') this.scrollToFirstInvalidControl('userLanguage');
private scrollToFirstInvalidControl(formControlName: string) { const firstInvalidControl: HTMLElement = this.el.nativeElement.querySelector( "#fieldCardID_" + formControlName ); if (firstInvalidControl != null) { window.scroll({ top: this.getTopOffset(firstInvalidControl), left: 0, behavior: "smooth" }); fromEvent(window, "scroll") .pipe( debounceTime(100), take(1) ) .subscribe(() => firstInvalidControl.focus()); } } private getTopOffset(controlEl: HTMLElement): number { const labelOffset = 90; return controlEl.getBoundingClientRect().top + window.scrollY - labelOffset; }
html:
<div class="w-100 mt-2" fxLayout="row wrap" id="fieldCardID_firstName"> <div fxFlex="40" fxFlex.lt-sm="100" fxLayoutAlign="start center"><label>{{'General.first_name_label' | translate}}</label></div> <div fxFlex="60" fxFlex.lt-sm="100" fxLayoutAlign="end center"> <input formControlName="firstName" required maxlength="128"> </div> </div>
ps:
private el: ElementRef

浙公网安备 33010602011771号