I have a form to update customer object.
I have a select for the type of customer, I want to pre-select the current value when I get customer data. How can I do this ?
This is a part of my html form :
<div class="form-group">
<label for="type" class="req">Type</label>
<select class="form-control" ngControl="type">
<option *ngFor="#p of typecustomerlist" [value]="p.code">{{p.label}}</option>
</select>
<div [hidden]="type.valid" class="alert alert-danger">
Please select a type
</div>
</div>
<div class="form-group">
<label for="lastname" class="req">Last name</label>
<input type="text" ngControl="lastname" value="{{customer.Lastname}}" />
<div *ngIf="lastname.dirty && !lastname.valid" class="alert alert-danger">
<p *ngIf="lastname.errors.required">Lastname is required.</p>
</div>
</div>
I found the solution. I added this in my component ngOnInit()
method : this.type.updateValue(this.customer.type);
My component :
export class UpdateCustomerComponent implements OnInit {
myCustomerForm: ControlGroup;
lastname: Control;
type: Control;
constructor(routeParam: RouteParams, private dataService: ContactDataService, private builder: FormBuilder) {
this.lastname = new Control('',
Validators.compose([Validators.required])
);
this.type = new Control(this.customer != null ? this.customer.Type : null,
Validators.compose([Validators.required])
);
this.myCustomerForm = builder.group({
lastname: this.lastname,
type: this.type
});
}
ngOnInit() {
this.dataService.get(this.id).subscribe(data => {
this.customer = <ICustomer>JSON.parse(JSON.stringify(data));
this.lastname.updateValue(this.customer.Lastname);
this.type.updateValue(this.customer.Type);
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With