我有一个模板,它将运输方式显示为单选按钮,例如 运输方式通过服务加载。
我想将表单控件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>
真正的答案是:不要那样做
此处的模板用于说明如何显示数据并将用户操作绑定到组件逻辑,而不是单独执行逻辑。它很难测试,很难维护而且很丑。
您应该在组件中通过侦听可观察量来执行此操作,例如:
// 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 }}
它只会显示任何内容,但会进行分配。对于您的情况,我制作了一个堆栈闪电战,您可以在此处找到
我在示例中添加了一个 FormGroup 以使其工作并删除可观察逻辑以使其更易于实现:
主要的"模板逻辑">(伙计,它很痛!(是ngFor
内部:
<span *ngIf="idx === 0 && !group.get('shipping_method').value">
{{ group.get('shipping_method').setValue(shippingMethod.id)}}
</span>
如果FormGroup
中尚未设置任何值,则仅对第一项进行分配
但同样将此逻辑放在组件中。