使用异步数据加载在Angular2中选择选项

时间:2016-02-19 13:35:18

标签: typescript angular angular2-forms

我有一个表单来更新客户对象。

我有一个客户类型的选择,我想在获得客户数据时预先选择当前值。 我怎么能这样做?

这是我的html表单的一部分:

<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>

1 个答案:

答案 0 :(得分:7)

我找到了解决方案。我在我的组件ngOnInit()方法中添加了此内容:this.type.updateValue(this.customer.type);

我的组件:

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

    }

}