Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set option as selected in Angular2 with asynchronous data loading

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>
like image 785
AdrienTorris Avatar asked Mar 13 '23 05:03

AdrienTorris


1 Answers

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);
        });

    }

}
like image 130
AdrienTorris Avatar answered Mar 16 '23 10:03

AdrienTorris