mat error not display error on click of button. angular 7

890 views Asked by At

I am having problem to display error message in mat error. following is html code.

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>

here error is display when field is empty,but error for mediaUpinNotExist doesn't not display on click of add media button.

TS code

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');
          });
        }
      }
    }
  )
}
}

I have already used one solution- markAsTouched . formcontrol is markAsTouched in TS file but not display message.

when i once again click in input box than error message are displaying. also after clicking on add media button data is not displaying in table.

for table please see screenshot. when i once again click in input box than data is display in table.input box and table to display data

Edit :

I have also used following function :

/** 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();

this matcher i have used in mat input.

1

There are 1 answers

0
sangRam On BEST ANSWER

I have found solution for above question. don't know it is right solution or not, but it worked for me. i have added click event, which is called in component.

In HTML :

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

In Component :

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

settimeout function called in addMedia() function. data is displaying in table and error are also displaying.