Enabling or disabling a button dynamically in Ionic based on a conditional statement

I am looking to dynamically enable or disable buttons based on specific conditions. The data is retrieved from Firebase, and depending on the data, I will either enable or disable the button.

For example, if a user passes the First Quiz, I want to enable the next lesson's button and so forth. If the user does not pass the quiz, the button should remain disabled.

In my Typescript file:

this.currentUser = this.afAuth.auth.currentUser.uid;
this.lessonStatus = this.af.object("/Quiz/" + this.currentUser + "/First_Quiz", { preserveSnapshot: true });
 this.lessonStatus2 = this.af.object("/Quiz/" + this.currentUser + "/Sec_Quiz", { preserveSnapshot: true });
 this.lessonStatus3 = this.af.object("/Quiz/" + this.currentUser + "/Third_Quiz", { preserveSnapshot: true });
 this.lessonStatus4 = this.af.object("/Quiz/" + this.currentUser + "/Fourth_Quiz", { preserveSnapshot: true });

this.lessonStatus.subscribe(snapshots => {
  snapshots.forEach(snapshot => {
    console.log(snapshot.key);
    console.log(snapshot.val());
    this.arrayTest.push(snapshot.val());
  });
//Outputs "true"
  console.log(this.arrayTest[0].Passed)

  if (this.arrayTest[0].passed == true) {

    this.lessonUnlocked = [{
      name: "unlock",
      valid: true,
    }];

  }
  else {

    this.lessonUnlocked = [{
      name: "lock",
      valid: false,
    }];

  }
});
//The same logic applies for lessonstatus 2 to 4.

In my HTML:

<ion-list *ngFor="let x of lessonUnlocked">

<ion-item *ngIf = "x.valid == true">
<button [disabled]="!x.valid" ion-item (click)="Lesson1()">
<ion-icon name="{{x.name}}"></ion-icon> Lesson1
</button>
</ion-item>

 <ion-item *ngIf = "x.valid == true">
<button  [disabled]="!x.valid" ion-item (click)="Lesson2()">
<ion-icon name="{{x.name}}"></ion-icon> Lesson2
</button>
</ion-item>

<ion-item *ngIf = "x.valid == true">
<button ion-item (click)="Lesson3()">
<ion-icon name="lock"></ion-icon> Lesson3
</button>
</ion-item>

The issue at hand is that even though the data in Firebase is set to true, the button remains disabled. It appears that the first if statement mentioned below is not being executed:

 else {

    this.lessonUnlocked = [{
      name: "lock",
      valid: false,
    }];

  }

Answer №1

Consider trying out the following options:

Utilize ApplicationRef.tick() for checking the full component tree, similar to Angular 1's $rootScope.$digest()

Opt for ChangeDetectorRef.detectChanges() to only check this component and its children, much like $scope.$digest()

Make sure to use one of these methods after updating your data from the subscribe method in order to reflect the changes in the view.

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

Enhance your Angular app by dynamically adding classes to existing classes on a host component

How can I dynamically add a class to the host component of this angular component? @Component({ selector: 'test', templateUrl: './test.component.html', styleUrls: ['./test.component.scss'], encapsulation: ViewEncapsulation ...

In Angular, what is the best way to update the quantity of an item in a Firestore database?

Whenever I attempt to modify the quantity of an item in the cart, the quantity does not update in the firestore database. Instead, the console shows an error message: TypeError: Cannot read properties of undefined (reading 'indexOf'). It seems li ...

Is the provided code snippet considered a function-statement, function-expression, and function-expression-statement?

Currently, I am examining some code snippets from the EcmaScript.NET project. Specifically, I am delving into the definitions within FunctionNode.cs file. The comment above the definitions provides a detailed explanation of the three types of functions tha ...

What is the process for encrypting and decrypting image files over the internet?

I'm currently developing a web application that requires loading images into a canvas object, followed by extensive manipulation. My goal is to conceal the original source image file (a jpeg) in such a way that users on the client side cannot access i ...

c# simulating button click through injected JavaScript

Greetings, I'm seeking assistance in replicating a specific button click on a website. Here is the code for the button: <button type="button" class="btn btn-link btn-xs" onclick="getComponents('188855', '5a0f44a9d70380.12406536&apo ...

Button click causing TextField to print incorrectly

I am working on implementing a feature in my react application where users can input a search term, and upon pressing the button, it will be used to perform a search. The text input field and button are utilizing material-ui components. At this stage, I si ...

No results found by Mongoose find() method

I've set up a route that utilizes a model named Todo as shown below: app.get('/api/todos', function(req, res) { Todo.find({},function(err, todos) { if (err) res.send(err); console.log("number of todos " + tod ...

Angular 14 troubleshooting: Issues with using getRawValue() in IndexOf function

In this scenario, I have a straightforward Person interface defined as: import { FormArray, FormControl, FormGroup } from '@angular/forms'; import { Address } from './address'; export class Person { id: FormControl<number>; n ...

Is your prop callback failing to return a value?

I am currently utilizing a Material UI Table component in my ReactJS project and I would like to update a state variable whenever a row is selected or deselected. The Table component has an onRowSelection prop that gets triggered each time a row is is sele ...

What is the most effective way to eliminate just the last underscore in a string by employing the

I am currently facing an issue with table cell editing. I have the following code that removes all underscores (_) from a string if it contains "test_1_". However, my requirement is to only remove the last underscore and have the string appear as "test_1". ...

Ensuring a consistently positioned footer at the bottom

I understand that this might not seem like a significant issue, but I'm encountering some difficulties. In my main.html file, there are three divs. The first div contains the navigation bar, the second div is an "empty" div that uses JQuery/Javascript ...

Using Vue's transition mode alongside v-for and v-if does not appear to function correctly

When using Vue with Vuetify, I am trying to dynamically change v-cards with the help of animate.css. However, I have run into an issue. The out-in mode is not working in this scenario as both fade-in and fade-out animations occur simultaneously. Is there a ...

Tips for importing a module such as 'MyPersonalLibrary/data'

Currently, I am developing a project with two packages using Typescript and React-Native: The first package, PackageA (which is considered the leaf package), includes a REST client and mocks: MyOwnLibrary - src - tests - mocks - restClientMoc ...

What impact does the //g flag in Regex JavaScript have on the program's state?

I recently had a question that was answered, but I'm still trying to grasp why the regex behaves in a certain way. According to w3schools, it explains: g: Perform a global match (find all matches rather than stopping after the first match) Okay, ...

The p-dialog lacks the proper styling and does not show or hide correctly

I am working on adding a feature where dragging and dropping an event in a calendar triggers a dialog box that requires the user to confirm if they want to postpone the event. However, I ran into an issue where the styling of my p-dialog is not defaulting ...

removing an item from a nested array through the use of the filter() method

I have been struggling to remove an element with a specific ID from a nested array. Are there any suggestions on how to effectively utilize the filter() method with nested arrays? The goal is to only eliminate the object with {id: 111,name: "A"}. Below ...

Determining when a checkbox changes state using HTML and JavaScript

My main objective is to display divX2 when the checkbox for x2 is checked, either by directly clicking on x2 or by clicking on the "Check All" checkbox. The functionality works as intended when the checkbox for x2 is clicked, but it fails to work when the ...

Reading properties of undefined in React is not possible. The log method only functions on objects

I'm currently facing an issue while developing a weather website using the weatherapi. When I try to access properties deeper than the initial object of location, like the city name, it throws an error saying "cannot read properties of undefined." Int ...

Utilize jQuery to manipulate a subset of an array, resulting in the creation of a new array through the use of

I have a string formatted like this: ItemName1:Rate1:Tax1_ItemName2:Rate2:Tax2:_ItemName3:Rate3:Tax3_ItemName4:Rate4:Tax4 (and so on, up to item 25). My task is to take an index provided by the user (for example, 2), retrieve the item at that index when ...

What is the best way to manage a custom child event that is triggered using this.$emit in a parent component, specifically within the <script> section of the .vue file?

In our project, we're utilizing vue and typescript, which means that our .vue files are structured very similarly to the layout outlined in this blogpost. One of our child components is emitting a custom event called changeType. I'd like to trig ...