0
votes

I am using *ngIf to display a component in my HTML. The variable that fires that *ngIf is changed after a button is clicked in a .subscribe() in the typescript file. Although it eventually displays the like it should, the user needs to click an extra time anywhere on the page after clicking the button to get it to show.

I have already tried .detectChanges() with a ChangeDetectorRef, get and set functions, and a separate function that changes the variable which is called from within the .subscribe().

HTML:

<mat-form-field>
    <input matInput #filename placeholder="Enter filename" (input)="filenameChange(filename.value)">
</mat-form-field>

<!--validateFilename() is the function with the .subscribe()-->
<button mat-raised-button (click)="validateFilename()">Validate</button>

<!--The div that should display automatically-->
<div *ngIf="filenameValid">
    <!--some code here-->
</div>

TYPESCRIPT:

validateFilename() {
  this.s3.getS3Response(this.bucketName, this.inputFilename).subscribe(response => {

      // some code here

      // the line that should instantly trigger the *ngIf
      this.filenameValid = true;
    }

    else {
      alert("Filename not valid. Please enter new filename.")
    }
  })
}

There are no error messages, it just requires a randomly placed extra click after the user submits a valid filename and clicks the 'Validate' button to display the following components hidden by the *ngIf

1

1 Answers

0
votes

I solved it myself for anyone looking for a solution. I wrapped the line in an ngZone.

import { Component, OnInit, NgZone } from '@angular/core';

// some code

constructor(private ngZone: NgZone) {};

//some code

validateFilename() {
  this.s3.getS3Response(this.bucketName, this.inputFilename).subscribe(response => {

      // some code here

      // the line that should instantly trigger the *ngIf
      this.ngZone.run(() => { this.filenameValid = true });
    }

    else {
      alert("Filename not valid. Please enter new filename.")
    }
  })
}