Reputation: 341
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)"
code:
public default_tax$:Observable<any>;
public tax$:Observable<Tax>;
ngOnInit(): void {
this.tax$ = this.db.list(`tax_rates`);
this.default_tax$ = this.db.object(`settings/default_tax_rate`);
}
template:
<select name="tax_rate" (ngModel)="default_tax.$key" (ngModelChange)="onSelect($event)">
<option *ngFor="let tax of (taxes$ | async)" [ngValue]="tax.$key">
{{tax.name}} - {{tax.rate}}
</option>
</select>
Firebase object:
account:
setttings:
default_tax_rate: "-somekey"
tax_rates:
"-somekey":
"name":"5.5"
"-someotherkey"
"anothername":"4.5"
Upvotes: 1
Views: 1661
Reputation: 341
Ok, I found out how to do this. I was writing the ngModel wrong. WRONG:
(ngModel)="default_tax.$key"
(ngModel)="(default_tax | async)"
CORRECT:
[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 http://blog.ng-book.com/the-ultimate-guide-to-forms-in-angular-2/
Upvotes: 3