John Hamman John Hamman - 2 months ago 63
Javascript Question

How do I set Angular 2 ngModel from a firebase observable on a select dropdown

I am trying to set the default value in a select dropdown from a firebase object using angularfire 2. But I don't know how to make it work with setting the default value of the select box. ngModel doesn't allow something like

(ngModel)="(default_tax | async)"


public default_tax$:Observable<any>;
public tax$:Observable<Tax>;

ngOnInit(): void {$ = this.db.list(`tax_rates`);
this.default_tax$ = this.db.object(`settings/default_tax_rate`);


<select name="tax_rate" (ngModel)="default_tax.$key" (ngModelChange)="onSelect($event)">
<option *ngFor="let tax of (taxes$ | async)" [ngValue]="tax.$key">
{{}} - {{tax.rate}}

Firebase object:

default_tax_rate: "-somekey"


Ok, I found out how to do this. I was writing the ngModel wrong. WRONG:

(ngModel)="(default_tax | async)"


[ngModel]="(default_tax | async)?.$value" 

Note that ngModel is wrapped with [] instead of [()] or (). Brackets[] indicate input, where parenthesis() indicate output. Having both [()] is for two-way binding (both input and output).

A great guide to help understand this in more details is