【问题标题】:Set option as selected in Angular2 with asynchronous data loading使用异步数据加载在 Angular2 中设置选项
【发布时间】:2016-02-19 13:35:17
【问题描述】:

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

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

这是我的 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>

【问题讨论】:

  • 您可以为自己的问题添加一个答案,然后接受您自己的答案(经过一段时间的冷却时间)。这样,问题就不会永远悬而未决。
  • 好的,我现在就这样做
  • outch,延迟2天。我可以删除这个问题吗?
  • 别担心。试着记住你最终会接受它。

标签: typescript angular angular2-forms


【解决方案1】:

我找到了解决方案。我在我的组件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);
        });

    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-12
    • 1970-01-01
    • 1970-01-01
    • 2017-03-21
    • 1970-01-01
    • 2016-08-21
    • 1970-01-01
    • 2019-01-11
    相关资源
    最近更新 更多