I am new to angular and i'm having trouble binding data from a data service to FormGroup. I am able to access the properties in the view just fine but the same properties are undefined inside the controller where I try to create the form group and set it's initial form control values.
Model
export class Dog {
constructor(
id: number,
name: string,
age: number
) { }
}
Service
getDog(): Promise<Dog> {
return this.http.get(this.baseUrl + '/api/endpoint').toPromise().then(res.json());
}
Component I then call this service from my component like:
export class DogComponent implements OnInit {
form: FormGroup;
dog: Dog;
constructor(private service: DogService, private fb: FormBuilder) { }
ngOnInit(): void {
this.getData();
this.createForm();
}
getData() {
this.service.getDog().then(res => this.dog = res);
}
createForm() {
this.form = this.fb.group({
id: [this.dog.id],
name: [this.dog.name],
age: [this.dog.age]
});
}
}
View
<form [formGroup]="form">
<input formControlName="name" />
<input formControlName="age" />
</form>
I am able to set the input value like [value]="name" but I want to be able to set those in the createForm method. Any ideas why the properties are available to the view but not inside the controller