Skip to content

Instantly share code, notes, and snippets.

@kmturley
Created May 21, 2018 21:32
Show Gist options
  • Save kmturley/95cb72607a43ea851890f4074f883bbc to your computer and use it in GitHub Desktop.
Save kmturley/95cb72607a43ea851890f4074f883bbc to your computer and use it in GitHub Desktop.
Angular 6 + Firebase Reactive Forms
<form [formGroup]="form">
<input class="input" type="text" formControlName="title" (change)="save()" /><br/>
<input class="input" type="text" formControlName="content" (change)="save()" />
</form>
import { Component, OnInit } from '@angular/core';
import { AngularFireDatabase, AngularFireObject } from 'angularfire2/database';
import { Observable } from 'rxjs';
import { FormGroup, FormBuilder, Validators, AbstractControl } from '@angular/forms';
export class Item {
title = '';
content = '';
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
item: AngularFireObject<Item>;
form: FormGroup;
constructor(
private db: AngularFireDatabase,
private fb: FormBuilder
) {}
ngOnInit() {
// this.item = this.create();
this.item = this.load('-LD3ar4ZqhxSWObxmqsG');
this.form = this.fb.group({
title: ['', Validators.required],
content: ['', Validators.required]
});
this.item.valueChanges().subscribe(item => {
this.form.patchValue(item);
});
}
create(): AngularFireObject<Item> {
const key = this.db.list('/items').push(new Item()).key;
return this.db.object(`/items/${key}`);
}
load(key): AngularFireObject<Item> {
return this.db.object(`/items/${key}`);
}
save() {
if (this.form.status !== 'VALID') {
return false;
}
this.item.update(this.form.value);
}
}
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AngularFireModule } from 'angularfire2';
import { AngularFireDatabaseModule } from 'angularfire2/database';
import { AngularFireStorageModule } from 'angularfire2/storage';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { ReactiveFormsModule } from '@angular/forms';
import { environment } from '../environments/environment';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
ReactiveFormsModule,
AngularFireModule.initializeApp(environment.firebase),
AngularFireDatabaseModule,
AngularFireAuthModule,
AngularFireStorageModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment