I'm trying to have a formly select field display the existing value automatically but for some reason it doesn't show up. Here's a simplified example: stackblitz (formly's forked) and here's the code:
The only thing changing in my real code is that (i) the data's really coming from a server and (ii) the options look like: { label: string; value: someObject{} }
app.component.html:
<form [formGroup]="form" (ngSubmit)="submit()">
<formly-form
[model]="model"
[fields]="fields"
[options]="options"
[form]="form"
></formly-form>
<button
type="submit"
class="btn btn-primary submit-button"
[disabled]="!form.valid"
>
Submit
</button>
</form>
<br />
{{ form.value | json }}
app.component.js:
import { Component, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { FormlyFormOptions, FormlyFieldConfig } from '@ngx-formly/core';
import { Observable, of } from 'rxjs';
@Component({
selector: 'formly-app-example',
templateUrl: './app.component.html',
})
export class AppComponent implements OnInit {
form = new FormGroup({});
model = null;
options: FormlyFormOptions = {};
fields: FormlyFieldConfig[] = [
{
key: 'lastName',
type: 'input',
defaultValue: 'This is a default value',
props: {
label: 'Last Name (initialized via the model)',
},
},
{
key: 'candy',
type: 'select',
props: {
label: 'Favorite Candy (initialized via default value',
options: this.getOptions(),
},
},
];
ngOnInit(): void {
this.getModel().subscribe((model) => (this.model = model));
}
submit() {
alert(JSON.stringify(this.model));
}
getModel(): Observable<any> {
return of({
lastName: 'Smith',
candy: { label: 'Milky Way', value: 'milky_way' },
});
}
getOptions(): Observable<any> {
return of([
{ label: 'Snickers', value: 'snickers' },
{ label: 'Baby Ruth', value: 'baby_ruth' },
{ label: 'Milky Way', value: 'milky_way' },
]);
}
}