I use Firebase as database, and access it through AngularFire2.
This is the whole TodoComponent.ts
file so you get the full picture, but the main thing i need is in finishedTodo()
.
import { Component, OnInit} from '@angular/core';
import { AngularFire, FirebaseObjectObservable ,FirebaseListObservable } from 'angularfire2';
@Component({
template: `
<h2>ToDo</h2>
<input
#newTodo
[(ngModel)]="todoinput"
placeholder="add ToDo"
(keyup.enter)="addTodo(newTodo.value)"
type="text"
/>
{{ todoinput }}
<br>
{{ item | async | json }} ///here I am getting the value as a json string, but I don't know how to make it do what i need
<div *ngFor="let todo of todos | async">
{{todo.todo}}
<button (click)="deleteTodo(todo.$key)">Delete</button>
<button (click)="finishedTodo(todo.$key)">Finished</button>
</div>
`
})
export class ToDoComponent implements OnInit{
item: FirebaseObjectObservable<any>;
todos: FirebaseListObservable<any>;
constructor(private _af: AngularFire) {
}
ngOnInit(){
this.todos = this._af.database.list('hr/todos');
this.item = this._af.database.object('/hr/todos/1');
}
addTodo(newTodo: string){
this.todos.push({
todo: newTodo
} )
}
deleteTodo(key: string){
if(confirm("U sure u want to delete " + key + " ?")){
this.todos.remove(key)
}
}
finishedTodo(key: string, finished: boolean){
this.todos.update(key,{finished: true})
}
}
In finishedTodo() I am able to set finished = true
, but before that, I want to check if the Firebase field finished = true or false
, and make toggle work so I can add special css based on this condition.
How can I check for finished=true
value in Firebase with angularfire2?
Update - @Aaron Saunders Solution adapted to my file
isFinished;
finishedTodo(key: string, finished: boolean){
var snapshotFinished = this._af.database.object('hr/todos/'+ key,{ preserveSnapshot: true})
snapshotFinished.subscribe(snapshot => {
this.isFinished = snapshot.val().finished;
});
if (this.isFinished == false || this.isFinished == null){
this.todos.update(key,{finished: true});
console.log('is false');
}
else{
this.todos.update(key,{finished: false});
console.log('is true');
}
}
var i = this._af.database.object('/hr/todos/1', { preserveSnapshot: true })
i.subscribe(snapshot => {
console.log(snapshot.key)
console.log(snapshot.val().finished)
});
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.