Why isn't the Angular2 ngIf directive updating the DOM?

I am encountering issues with finding the right expression for ngIf to evaluate properly.

After following a basic Angularfire2 example, I have successfully managed to log in and out.

import { Component } from '@angular/core';
import { AngularFire } from 'angularfire2';

@Component({
  selector: 'app-root',
  template: `
  <div> {{ (af.auth | async)?.uid }} </div>
  <button (click)="login()">Login</button>
  <button (click)="logout()">Logout</button>
  `,
})
export class AppComponent {
  constructor(public af: AngularFire) {
    this.af.auth.subscribe(auth => console.log(auth));
  }

  login() {
    this.af.auth.login();
  }

  logout() {
     this.af.auth.logout();
  }
}

I am trying to adjust the code to display/hide the appropriate buttons based on the logged-in status. Although I can see that auth is toggling between null and object in the console, the DOM does not update accordingly.

This is my latest attempt:

<div> {{ (af.auth | async)?.uid }} </div>
<button *ngIf="!(auth | async)" (click)="login()">Login</button>
<button *ngIf="auth | async" (click)="logout()">Logout</button>

What could be the issue here? How can I ensure correct evaluation of this scenario?

Answer №1

UPDATE: It's important to keep track of the login status in your login and logout methods by subscribing to changes. You can do this by adding

this.af.auth.subscribe(auth => this.auth = auth);
to those methods.

I may not have much experience with Angularfire, but if the authentication status is toggling between null and a value, you can store and utilize that information. For example, instead of simply logging the output, you could subscribe to auth => this.auth = auth during the subscription process and then use it as follows:

<button *ngIf="auth == null" (click)="login()">Login</button>
<button *ngIf="auth != null" (click)="logout()">Logout</button>

This might not be the most efficient approach. Another option would be to create a boolean variable like isLogged and toggle button visibility based on its value.

There are probably better ways to handle this scenario, but these suggestions should provide some alternatives at least.

Answer №2

To gain a better understanding of the (af.auth | async)?.uid expression, I suggest exploring the functionalities of the AsyncPipe along with the safe navigation operator (?.)

template: `
<div [ngSwitch]="(af.auth | async)?.uid">
 <button *ngSwitchCase="null" (click)="login()">Login</button>
 <button *ngSwitchDefault (click)="logout()">Logout</button>
</div>`

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible for me to modify the appearance of the ion-searchbar in Angular?

Currently working on an angular ionic project and I'm looking to personalize the design of the ion-searchbar. In the default template, the search bar icon is positioned on the left side. My goal is to adjust the placement of the icon and have it situa ...

Having difficulties viewing the sidemenu icon on Ionic 3, despite enabling the menu through MenuController

I am trying to show the sidemenu icon on my Home page, which users can access from the Add-Contract page. Even though I have enabled the sidemenu in home.ts using this.menu.enable(true);, the icon is not visible. However, I can still swipe and access the ...

Creating a dynamic return statement in typescript: A step-by-step guide

I am looking to dynamically set a return value to a variable based on values retrieved from an API. The current function in question uses static values: this.markDisabled = (date: NgbDate) => { return (this.calendar.getWeekday(date) !== 5 && ...

Unable to create a new collection in Firebase Firestore

I encountered an issue while trying to add a collection in Firebase Firestore using the function .collection(doc).set. Despite finding the new user in authentication in Firebase, the collection was not created and the console displayed an error message. ...

The process of subscribing to a service in Angular

I currently have 3 objects: - The initial component - A connection service - The secondary component When the initial component is folded/expanded, it should trigger the expansion/folding of the secondary component through the service. Within the service ...

Angular: Eliminating code duplication through service transfer

One code snippet that I frequently use when booting the app is (ngOnInit): this.route.queryParamMap.subscribe( params => { const id = params.get('id'); if (id) { this.contactsService.GetContactByUserId(id) .subscribe( ...

The Angular router-outlet is refusing to display any content

I am new to Angular and currently learning through a lecture with hands-on practice. I have written the code below as instructed by my teacher, but it's not displaying anything on the screen. Can someone please assist me? app.module.ts : @NgModule({ ...

Angular 4 enum string mapping reversed

Here is an example of a string enum: export enum TokenLength { SIX = '6', EIGHT = '8', } I am trying to retrieve the string value 'SIX' or 'EIGHT' by reverse mapping this enum. I have attempted various methods: ...

Sample Angular component showcasing arguments and content within a storybook MDX preview

We showcase our angular components using Storybook and typically utilize the MDX format for this purpose When dealing with an angular component that needs content and accepts properties (via the "Controls" Plugin), I am facing difficulties in implementing ...

Optimizing Angular Performance with Trackby in Dual Lists

How can I write two ngFor lists with trackby to prevent elements from being recreated when moving between the lists? I know that trackby helps in avoiding recreation of elements within a single list, but is there a way to achieve this across multiple list ...

NGRX Store: struggling to retrieve value from store

Currently, I am working on setting up a basic NGRX store. The goal is to have a value in my Store (specifically called chipSelected: string), display that value in AA.component.ts, and be able to change it in BB.component.ts using a button click. In esse ...

How to dynamically disable a checkbox in Angular reactive forms depending on the value of another checkbox

I am attempting to deactivate the checkbox based on the value of other checkboxes. Only one of them can be activated at a time. When trying to activate one of the checkboxes, I encounter an issue where the subscribed value is being repeated multiple times ...

Issue with Child Component Loading Once CUSTOM_ELEMENTS_SCHEMA is Added to App Module

One of my components, known as HostComponent, works perfectly fine when set as the startup component in my application. However, I decided to create a new module called AppModule and nested the host component within the app component: import { Component, ...

A single element containing two duplicates of identical services

I am encountering an issue with my query builder service in a component where I need to use it twice. Despite trying to inject the service twice, it seems that they just reference each other instead of functioning independently, as shown below: @Component( ...

Setting a default value and object ID in Angular's reactive forms for a select dropdown

Having an issue with validating a default value in a selector that serves as a message to select an option. The problem arises from the validation of this option, as it is linked to the object ID of another collection in the database (mongoose-express js). ...

Micro Frontend: Implementing a Pubsub System for Scalable Front-End Architecture

Currently, I am developing a large-scale application using the innovative micro front end architecture. The application is split into 5 Micro Apps: (micro-app-A (developed in Vue), micro-app-B (built with Vue), micro-app-C (using Angular), micro-app-D (cre ...

Angular JSON Format Output: A Comprehensive Overview

I have noticed that the JSON output format currently being used may lead to errors in the application. I am trying to figure out how to achieve a different format for my code below. While I can see my data, the objects are not nested under the topics as ex ...

Minimize the cyclomatic complexity of a TypeScript function

I have a typescript function that needs to be refactored to reduce the cyclometric complexity. I am considering implementing an inverted if statement as a solution, but it doesn't seem to make much of a difference. updateSort(s: Sort) { if (s.ac ...

Discover the best way to cycle through bootsrap modal dialogs using angular

Within my component.ts file, there exists an array: dummyData = ['1', '2', '3']; The objective is to iterate through this array and generate 3 modals displaying values 1, 2, and 3 respectively. Here's a snippet of the ...

Invoke a function of a child component that resides within the <ng-content> tag of its parent component

Check out the Plunkr to see what I'm working on. I have a dynamic tab control where each tab contains a component that extends from a 'Delay-load' component. The goal is for the user to click on a tab and then trigger the 'loadData&apo ...