Reputation: 2463
I have a form group with a few radio form controls. One radio for photo, drone, floorplan, etc.
this.services.photo
for instance is an array of services. Each radio group lets you select an option from each. Ie, 1 photo choice, 1 drone choice, 1 floorplan choice.
I'm already able to fetch my data from a service but I'm not able to prepopulate the form with the data. How do I loop through my service data collection and set the value of the radio buttons? What I'm doing now is not working. Or is there a better way to set things up to make it simpler.
export class CartComponent implements OnInit {
public myForm:FormGroup;
public services;
stepName = "cart";
constructor(private fb:FormBuilder, private bookerData:BookerService, private settings:FirebaseService, private route:ActivatedRoute, private zone:NgZone) {
this.services = this.route.snapshot.data['cartSettings'].services
}
ngOnInit() {
this.myForm = this.fb.group({
photo : new FormControl(this.services.photo),
drone: new FormControl(this.services.drone),
floorplan: new FormControl(this.services.floorplan),
video: new FormControl(this.services.video)
})
if(this.bookerData.isValidStep(this.stepName)){
let data = this.bookerData.getStepData(this.stepName)
console.log(data);
_.forOwn(data, (v, k)=>{
this.myForm.get(k).patchValue(v)
})
}
}
}
Upvotes: 1
Views: 64
Reputation: 2454
The FormControl constructor accepts an 'initial state' value you could use.
email: new FormControl('default value', Validators.compose([
Validators.required,
Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')
])),
if your data comes later than initiation (ngOnInit) I would suggest an ngModel binding, to update an value when you get the form data.
Upvotes: 2