简体   繁体   中英

Style binding not updating on FontAwesome spinner icon in Angular 4

This seems like a silly problem, but after investigating and doing all kinds of tests, I don't understand why this happens.

I have a Send button that should show a spinner while sending, and then go back to not showing it.

<button (click)="sendCSV()" class="btn btn-primary btn-sm"><i class="fas fa-spinner fa-spin" [style.visibility] = "sendingEmails ? 'visible' : 'hidden'"></i>   Send</button>
{{sendingEmails}}

I added {{sendingEmails}} below the button to verify that the variable is changing properly, and it is. In my component, I have a sendingEmails var that is originally false, and:

sendCSV() {

        this.sendingEmails = true;
        this.eventsService.sendGuestlistByEmail(this.eventId).subscribe(
            res => {
                this.sendingEmails = false;
                console.log(res);
            }, 
            err => {
                this.sendingEmails = false;
                console.log("Error.");
            }
        );
    }

The problem is that when I click send, the data binding will update properly (false-true-false), but the styles stay as if I had never clicked.

In case it matters, I'm using Font Awesome 5 for the spinner.

I also tried

<i class="fas fa-spinner fa-spin" *ngIf="sendingEmails"></i>

This will lead to the spinner multiplicating every time I send the emails, and never actually disappearing after the first time.

Any idea why this could be?

Thank you all for your input and suggestions.

It turns out that the problem was not Angular, but FontAwesome. I recently upgraded to FontAwesome 5, which works with SVGs, instead of CSS. So, FontAwesome was turning my <i> into an SVG, and therefore, not updating properly.

It was a very silly problem, but it might come up for people who were used to the old FontAwesome, so I wanted to leave my "solution".

It's as simple as doing:

<span [style.visibility] = "sendingEmails ? 'visible' : 'hidden'">
    <i class="fas fa-spinner fa-spin"></i>
</span>

try to use ChangeDetectorRef.detectChanges() to run change detection on the component

  constructor(private changeD: ChangeDetectorRef) {}

  sendCSV() {
   this.sendingEmails = true;
    this.eventsService.sendGuestlistByEmail(this.eventId).subscribe(
        res => {
            this.sendingEmails = false;
            this.changeD.detectChanges();
            console.log(res);
        }, 
        err => {
            this.sendingEmails = false;
            console.log("Error.");
        }
    );
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM