首页 > 解决方案 > 从模板中设置表单控件的值

问题描述

我有一个模板,该模板将运输方式显示为单选按钮,例如通过服务加载运输方式。

我想将 FormControlshipping_method的值设置为第一个选项的 id 我该怎么做?

<div class="form-row" *ngIf="shippingMethods$ | async; let shippingMethods; ">
  <div class="form-group radio" *ngIf="shippingMethods.length > 0">
    <h2>Versandart:</h2>
    <label *ngFor="let shippingMethod of shippingMethods; let idx = index" for="method-{{ shippingMethod.id }}">
      <input formControlName="shipping_method" type="radio" value="{{ shippingMethod.id }}"
        id="method-{{ shippingMethod.id }}" [checked]="idx === 0">
      <i class="checkbox"></i>
      <span>{{ shippingMethod.label }}</span>
    </label>
  </div>
</div>

标签: angular

解决方案


真正的答案是:不要那样做

该模板用于告诉您如何显示数据并将用户操作绑定到您的组件逻辑,而不是单独执行逻辑。它难以测试,难以维护且丑陋。

你应该在组件中通过听你的 observable 来做到这一点:

// after initialisation of your observable
shippingMethods$.tap(methods => {
    // we use tap to not make a double subscription
    // group is your FormGroup
    if (!this.group.get('shipping_method').value) {
        this.group.get('shipping_method').setValue(methods[0].id);
    }
});

但是,如果你真的想要你可以像这样在模板中执行这样的分配逻辑:

{{ myvar = value }} 

除了进行分配外,它不会显示任何内容。对于你的情况,我做了一个 stackblitz,你可以在这里找到

我在示例中添加了一个 FormGroup 以使其工作并删除 Observable 逻辑以使其更易于实现:

主要的“模板逻辑” (真疼!)是里面的ngFor

<span *ngIf="idx === 0 && !group.get('shipping_method').value">
    {{ group.get('shipping_method').setValue(shippingMethod.id)}}
</span>

如果在FormGroup

但是再次将此逻辑放在组件中。


推荐阅读