Displaying Firebase values in an Angular 2 list is a breeze

Here is the functionality to load, add, and mark ToDo as Finished:

    todos: FirebaseListObservable<any>;

    ngOnInit(){
        this.todos = this._af.database.list('todos')
    }

    addTodo(newTodo: string){
        this.todos.push({
            todo: newTodo
        } )
    }

    finishedTodo(key: string, finished: boolean, isFinished: boolean){

        var snapshotFinished = this._af.database.object('todos/'+ key,{ preserveSnapshot: true})

        snapshotFinished.subscribe(snapshot => {          
            isFinished = snapshot.val().finished;  
        });

        if (isFinished == false || isFinished == null){
            this.todos.update(key,{finished: true});
            isFinished = true;
            console.log(isFinished);
        }    
        else{
            this.todos.update(key,{finished: false});
            isFinished = false;
            console.log(isFinished);
        }
    }

And now let's take a look at the HTML code:

<div *ngFor="let todo of todos | async">

    <span> {{todo.todo}} </span>

    <button (click)="finishedTodo(todo.$key)">Finished</button>
</div>  

When you click the Finished button, it toggles the finished value in Firebase. However, you may be wondering how to reflect this change in the Angular2 list.

So, my question is: when displaying the list of todos, how can I determine the finished value from within Firebase for each item in the list?

Answer №1

To include a checkbox in your template HTML and utilize todo.finished for the boolean value of finished, follow these steps.

<div *ngFor="let todo of todos | async">
  <input type="checkbox" [(ngModel)]="{{ todo.finished }}">
  <span>{{ todo.todo }}</span>
  <button (click)="finishedTodo(todo.$key)">Complete</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

Navigating with the Angular router leads to an unexpected destination: "mat-radio-group-0=true"

I'm facing an issue with a close button in my HTML template that triggers a close() function in the component: HTML template: <div> <label id="radio-group-label">Please specify: </label> <mat-radio-grou ...

Convert the XML response from an API into JSON

Is there a way to convert my XML response into JSON using Angular? This is the response I am working with: <?xml version="1.0" encoding="utf-8"?> <string xmlns="http://tempuri.org/"><?xml version="1.0" encoding="utf-8"?&gt; &lt;Fer ...

The disappearing act of embedded Twitter timelines in Ionic 2

My code displays the timeline initially, but it disappears when I navigate away from the view. Can anyone help me troubleshoot this issue? Upon first visit to the view, the timeline is visible, but upon returning, it disappears. Below is the code snippet ...

What is the issue with this asynchronous function?

async getListOfFiles(){ if(this.service.wd == '') { await getBasic((this.service.wd)); } else { await getBasic(('/'+this.service.wd)); } this.files = await JSON.parse(localStorage.getItem('FILENAMES')); var ...

Issue with bootstrap modal new line character not functioning properly

Is there a correct way to insert a new line for content in a modal? I have this simple string: 'Please check the Apple and/or \nOrange Folder checkbox to start program.' I placed the '\n' newline character before "Orange," e ...

How to Customize the Select Dropdown in Angular Material 2

I am having trouble customizing the default style of this component : https://material.angular.io/components/component/select It contains various classes such as .mat-select-placeholder, .mat-select-value However, I cannot find any information in thei ...

Why does Angular throw a NullReferenceException when calling User.FindFirst(ClaimTypes.NameIdentifier), whereas Postman executes the same code without any

I'm currently troubleshooting a NullReferenceException in a .NET Core API and Angular application, but I've hit a roadblock. The specific issue arises when trying to update the "About" section of a User. Take a look at the text area screenshot ...

Is it possible to selectively mock certain components of an external module using jest?

I am totally new to using Jest, especially in regards to unit tests, and I am struggling to write a test for a specific scenario. I know that you can mock an external module like this.. jest.mock('@organisation/library', () => ({ Database: j ...

Exploring the Capabilities of TypeScript 1.8 in Visual Studio 2017

Recently, I've encountered an issue with my Visual Studio project that was created using TypeScript 1.8 in Visual Studio 2015. Upon upgrading to Visual Studio 2017 and attempting to open the project in the new IDE, I noticed that the TypeScript versio ...

React Component - Element with an undefined value

When I tried implementing an Ionic Modal as a React Component, I encountered the following error message: Type '({ onClose, tipo }: PropsWithChildren<{ onClose: any; tipo: number; }>) => Element | undefined' is not assignable to type & ...

Retrieve a result from an observable within a function

While attempting to solve what appears to be a simple problem, I'm struggling to find any solutions in my research. The issue arises when trying to subscribe to an Observable within a method and return a value from it. Here is an example of what I h ...

Facing a 404 error when importing a 3rd party module into Angular 4+ due to the base tag

Currently, I am integrating Angular into my MVC application. To accomplish this, I have included a script tag in my layout view to reference the Angular source code, and so far everything is running smoothly. However, I encountered an obstacle when attemp ...

issue with Angular: Unable to set both minimum and maximum values in the same input field for date type

I have been attempting to apply minimum and maximum values to an Angular code snippet, here is what I have: <input type="date" class="form-control" style="width: 30%" [disabled]="!dateSent" min="{{dateSent|date:&apo ...

Tips for effectively simulating the formik useFormikContext function while writing unit tests using jest

I've created a simple component (shown below) that aims to fetch data from the Formik FormContext using the useFormikContext hook. However, I'm facing some challenges when writing unit tests for this component. It requires me to mock the hook, w ...

Steps for linking HTTP requests in Angular 2 depending on the type of response

My attempt to create an api call from a remote server and then, if an error occurs, make another request from my local server is not working as expected. I am encountering errors and need help to determine if my approach is feasible. Here is the code snip ...

Encountering an error: "Unable to assign the 'id' property to an undefined object while attempting to retrieve it"

I'm running into an issue while attempting to retrieve a specific user from Firebase's Firestore. export class TaskService { tasksCollection: AngularFirestoreCollection<Task>; taskDoc: AngularFirestoreDocument<Task>; tasks: Obs ...

Convert potentially undefined boolean into a boolean by utilizing "!!"

Just had a thought - when dealing with a potentially undefined boolean variable, is it advisable to cast it as a boolean using the double exclamation mark? Consider this interface: interface Example { id: number; isDisabled?: boolean; } We then have ...

How should trpc query calls be implemented in a Next.js application for optimal performance?

Transitioning from pure frontend React to Next.js, I am currently working on implementing trpc calls to the backend. While this is a familiar process for me, it seems that the approach I've been using may not be appropriate in this case. const [weight ...

For each array element that is pushed, create and return an empty object

I am encountering an issue with an array where the objects are being generated by a push operation within a function. Despite successfully viewing the objects directly in the array, when I attempt to use forEach to count how many times each id uses the ser ...

Node.js server containerized with Docker: deleted express route remains accessible

I recently developed a Twitch Chat Bot using Dockerized (docker compose), Node.js v16 with express. To create an authorize-page for users to authorize my bot on the Twitch API, I utilized the route /auth/request: this.serverUrl = serverUrl; this.port = po ...