div 元素可以使用 formControlName 吗?

Can div element use formControlName?

我正在使用 angular 2。我正在处理一个需要显示地址列表和 select 其中之一的表单。我最初使用的是单选按钮,但要求已更改,我们将其显示为 div 块。我想知道我们是否可以使用

<div formControlName="controlName">

在像上面那样的 div 元素中?如果不是那么我们如何使用带有 div 的表单控件?

此外,当 w 单击一个地址块时,它应该更改背景颜色以将显示更改为 selected,并且该块的右上角应出现一个勾号。我可以在不使用循环时显示此样式更改,但我无法在地址循环中使用样式更改

这种形式有多个这样的块,在每个块中地址 selection 是强制性的,在每个块中我们将有多个地址。所以有一个主循环,其中有地址循环。

这适用于单选按钮,但我不确定 div 是否也是如此。请指导我。

您可以使用 ControlValueAccessor,并创建一个 component/directive 作为新的 自定义表单控件

import { Component, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Component({
  selector: 'div-select-buttons',
  providers: [
    {
        provide: NG_VALUE_ACCESSOR,
        useExisting: forwardRef(() => DivSelectButtonsComponent),
        multi: true
    }
  ],
  template: `<div>your inputs</div>`,
})
class DivSelectButtonsComponent implements ControlValueAccessor {
    // implementation ControlValueAccessor interface
}

然后像这样将其用作表单控件:

<form [formGroup]="form">
    <div-select-buttons formControlName="controlName"></div-select-buttons>
</form>

根据需要,我们需要更改项目的显示。因此,与其创建一个新组件来将 formcontrol 添加到 div,不如添加一个隐藏的单选按钮并使用抽象控件推送值....感谢大家的投入....