angular - 从模板中设置表单控件的值
问题描述
我有一个模板,该模板将运输方式显示为单选按钮,例如通过服务加载运输方式。
我想将 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>
解决方案
真正的答案是:不要那样做
该模板用于告诉您如何显示数据并将用户操作绑定到您的组件逻辑,而不是单独执行逻辑。它难以测试,难以维护且丑陋。
你应该在组件中通过听你的 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
但是再次将此逻辑放在组件中。
推荐阅读
- twitter-bootstrap - 我在哪里可以找到所有引导程序图标?
- r - 如何从数据集中取出一列,从另一个数据集中取出一列以过滤掉特定的东西?
- c++ - 在 OpenMP 中共享作用域变量
- html - Laravel css 有时不加载
- javascript - 是否有 CSS 选择器来选择具有数字作为 id 的 div
- git - 将新版本的存储库合并到我当前的版本中
- javascript - 我还需要在 React 的 then 块中使用 async/await
- jquery - 如何通过 jQuery 或 C# 在 input type='datetime-local' 或 Textmode='Datetimelocal' 上设置最小和最大日期时间动态
- reactjs - featuresImage 没有出现在 GraqhiQL 和 Gatsby 中
- c# - Asp.Net MVC 无法访问此站点错误