Home > Software design >  Need to show *ngIf directive element in UI only after API response
Need to show *ngIf directive element in UI only after API response

Time:09-16

I have a validation API and based on the error, I'm highlighting the field, but before validation is completed it is showing no errors only. How can restrict it.

My HTML-

                </mat-header-cell>
                <mat-cell style="max-width: 6%;" *matCellDef="let element; let i=index">
                    <button *ngIf="!element.HAS_ERROR" mat-icon-button>
                        <span  style="color: #55bd55;">done</span>
                    </button>// this element is showing till before validation API response. but I need to restrict till API response.
                  
                    <button mat-icon-button color="warn" *ngIf="element.HAS_ERROR" (click)="openConflictDialog(i)">
                        <span >
                          info
                        </span>
                    </button>
                </mat-cell>
            </ng-container>

TS-

 asyncReq(element:any){
      this.conflictData = null;
        //For all day
        let startDate:any;
        let endDate:any;
        startDate = this.easternToUtc.transform(moment(element.START_TIME).format('YYYY/MM/DD 00:00:00'), this.selectedTimeZone);
        endDate =  this.easternToUtc.transform(moment(element.END_TIME).format('YYYY/MM/DD 23:59:59'), this.selectedTimeZone);
      return  new Promise((resolve, reject) => {
        
        let requestPayload = zipObj(['USER_ID','AMENITY_TYPE_ID','AMENITY_ID','START_TIME', 'END_TIME', 'BUILDING_ID', 'AMENITY_NAME'],
        [element.USER_ID,element.AMENITY_TYPE_ID,element.AMENITY_ID,startDate,
          endDate, element.BUILDING_ID, element.AMENITY_NAME]);
        this.http.post(`${environment.reservationValidation}`, requestPayload).pipe(take(1)).subscribe(e => {
          }, (e:any) => {
            console.log(e);
            element.ERROR_TYPE = e.error?.message;
            element.HAS_ERROR = true;
            this.conflictData = e.error?.reservationdata;
          })
        })
    }

CodePudding user response:

Check this example. Stackblitz NgIf Sample

First set an Observable and subject and call it with async pipe in html file.

Hope this helps!

CodePudding user response:

Simply take one global boolean type variable in .ts file, after getting the successful API response, based on whatever the key is needed from response, we can make our variable to true. You can use this variable in your *ngIf directive to make it visible or hidden.

  • Related