从模板

时间:2018-07-03 14:33:41

标签: angular

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

我想将FormControl shipping_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>

1 个答案:

答案 0 :(得分:1)

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

此处的模板告诉您如何显示数据并将用户操作绑定到组件逻辑,而不是自己执行逻辑。它很难测试,难以维护且很难看。

您应该在组件中通过监听可观察到的声音来实现这一点,

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

除进行分配外,将不显示任何内容。对于您的情况,我进行了一次突击,可以找到here

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

主要的“模板逻辑” (真让人痛心!)ngFor中的

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

如果FormGroup中没有设置任何值,则仅对第一项进行分配

但是再次将此逻辑放置在组件内部。