4

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>
4
  • You can add an answer to your own question and then accept your own answer (after some cool-down time). This way the question wouldn't stay open as unanswered forever. Commented Feb 19, 2016 at 13:52
  • ok, I do this right now Commented Feb 19, 2016 at 13:52
  • outch, the delay is 2 days. May I have to delete this question ? Commented Feb 19, 2016 at 13:54
  • Don't worry. Just try to remember that you accept it eventually. Commented Feb 19, 2016 at 13:57

1 Answer 1

7

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

    }

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.