0

我在 mat 错误中显示错误消息时遇到问题。以下是html代码。

HTML

<form [formGroup]="addTenderLicneseForm" autocomplete="off">
<mat-form-field fxFlex="0.7 1 0%;" appearance="outline">
<mat-label>Media Upin</mat-label>
<input matInput formControlName="tender_media_upin" [errorStateMatcher]="matcher" style="text-transform: uppercase"(change)="addTenderLicneseForm.patchValue({tender_media_upin: $event.target.value.toUpperCase()})" minlength="16" maxlength="16" required
        (keypress)=_checkOnlyAlphaAndNum($event)>
<mat-error *ngIf="addTenderLicneseForm.controls['tender_media_upin'].hasError('required') && addTenderLicneseForm.controls['tender_media_upin'].touched">
        Please Enter Media Upin.</mat-error>
<mat-error *ngIf="addTenderLicneseForm.controls['tender_media_upin'].hasError('mediaUpinNotExist')&& addTenderLicneseForm.controls['tender_media_upin'].touched"">
        Not Found, please recheck or add media first</mat-error>
</mat-form-field>
<button mat-raised-button color="primary" type="button" [disabled]="addTenderLicneseForm.get('tender_media_upin').invalid" (click)="addMedia()">Add Media</button>
</form>

当字段为空时显示此错误,但单击添加媒体按钮时不会显示mediaUpinNotExist的错误。

TS代码

addMedia(){
if(this.tender_media_upin.valid){
  this.mediaUpinServerSiteErr = false;
  this.mediaUpinNotExist = false;
  this.mediaUpinCannnotAdd = false;
  let tender_media_upin = this.tender_media_upin.value;
  let tender_media_upin_Data = {
    e024173547eb49631f29a5db0535fc450d8f129e4e04c9223499614e62d74bda : tender_media_upin.trim()
  }
  this.tenderMasterSer.getMediaMasterDetails(tender_media_upin_Data).subscribe(
    res => {
      if(res.status == 'success'){
        if(res.code == 1){//upin exits
          var media_upin_data = res.data;
          console.log('media_upin_data',media_upin_data);
          var media_status = media_upin_data.status;
          if(media_status == 2){//expired
            if(this.media_upin_len > 0){
              this.add_tenedr_media();
            }
            const formArr = this.tender_media;
            if(formArr.at(this.media_upin_len)){
              formArr.at(this.media_upin_len).patchValue({
                media_mst_id : media_upin_data.media_mst_id,
                media_upin: media_upin_data.upin,
                media_address: media_upin_data.location,
                zone_id: media_upin_data.zone_id,
                media_width: media_upin_data.width,
                media_height: media_upin_data.height,
                latitude: media_upin_data.latitude,
                longitude: media_upin_data.longitude
              });
            }else{
              formArr.push(this.fb.group({
                media_mst_id : media_upin_data.media_mst_id,
                media_upin: media_upin_data.upin,
                media_address: media_upin_data.location,
                zone_id: media_upin_data.zone_id,
                media_width: media_upin_data.width,
                media_height: media_upin_data.height,
                latitude: media_upin_data.latitude,
                longitude: media_upin_data.longitude
              }))
            }
            this.tender_media_data.push(media_upin_data);
            this.media_upin_len++;
            this.tender_media_upin.markAsTouched();
            if (this.tender_media_upin.touched) {
              console.log('touched  1', this.tender_media_upin.touched)
            } else {
              console.log('touched  2', this.tender_media_upin.touched)
            }
          }else{
            this.mediaUpinCannnotAdd = true;
          this.tender_media_upin.setErrors({
            mediaStatusCurrent: true
          })
            this.tender_media_upin.markAsTouched();
            if (this.tender_media_upin.touched) {
              console.log('touched  1', this.tender_media_upin.touched)
            } else {
              console.log('touched  2', this.tender_media_upin.touched)
            }
          }
        }else if(res.code == 2){//upin does not exits
          this.tender_media_upin.markAsTouched();
          if (this.tender_media_upin.touched) {
            console.log('touched  1', this.tender_media_upin.touched)
          } else {
            console.log('touched  2', this.tender_media_upin.touched)
          }
          this.mediaUpinNotExist = true;
          this.tender_media_upin.setErrors({
            mediaUpinNotExist: true
          })
        }
      }
    },
    err => {
      console.log('err',err);
      if (err instanceof HttpErrorResponse) {
        if(err.status == 400){
          this.mediaUpinServerSiteErr = true;
          this.tender_media_upin.setErrors({
            mediaUpinServerSiteErr: true
          })
        }
        if (err.status == 401) {
          localStorage.removeItem('9ce00eac14eb70fe28bee5ae40b7d827');
          this.router.navigate(['/sessions/signin']).then(() => {
            this.toast.error('Kindly Login', 'Unauthorized');
          });
        }
      }
    }
  )
}
}

我已经使用了一种解决方案——markAsTouched。formcontrol 在 TS 文件中被 markAsTouched 但不显示消息。

当我再次单击输入框时,将显示错误消息。单击添加媒体按钮后,数据也未显示在表格中。

表格请看截图。当我再次单击输入框时,数据将显示在表格中。输入框和表格显示数据

编辑 :

我还使用了以下功能:

/** Error when invalid control is dirty, touched, or submitted. */
export class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    const isSubmitted = form && form.submitted;
    return !!(control && control.invalid && (control.dirty || control.touched || isSubmitted));
  }
}
matcher = new MyErrorStateMatcher();

这个匹配器我在垫子输入中使用过。

4

1 回答 1

0

我已经找到了上述问题的解决方案。不知道这是否是正确的解决方案,但它对我有用。我添加了单击事件,该事件在组件中调用。

在 HTML 中:

<div #divClick (click)="itsClick()"></div>

在组件中:

 @ViewChild('divClick') divClick: ElementRef;
setTimeout(() => {
            this.divClick.nativeElement.click();
          });
itsClick() {}

在 addMedia() 函数中调用的 settimeout 函数。数据显示在表格中,错误也显示出来。

于 2021-08-18T13:22:14.300 回答