angular - 在新的 Angular 2 表单中将 NgModel 绑定(bind)到 FormControl

标签 angular angular2-directives angular2-forms

我目前正在将我的 Angular 2 表单转换为最近引入的表单 API,但是我无法将嵌套在指令中的输入连接到 FormGroup 中定义的控件。

我在组件中为这样的表单定义表单和验证(在 Typescript 中):

model = {
   foo: 12.34
}

amount: : FormControl = new FormControl('', Validators.required);

ngOnInit() {
    this.fooFormGroup = new FormGroup({
        amount: this.amount,
      });    
    this.form.addControl("formGroup", this.formGroup);
}

在 HTML 中,我使用 name-property 将表单连接到输入。这有效,除非我使用嵌入这样的输入的自定义指令:
<fieldset>
    <form [formGroup]="fooFormGroup ">
         <custom-input-for-decimals [decimals]="4" [value]="model.amount" (valueChange)="model.amount = $event" controlname="amount"></custom-input-for-decimals>
    </form>
</fieldset>

在指令中,我更新并预先格式化了 ngModel 值(例如,截断 4 位以上的小数)。它需要一个 controlname 属性,该属性在模板中设置为 name 属性:
template: '<input type="text" [(ngModel)]="inputValue" (blur)="onBlur()" name="{{controlname}}">'

但这不会在 formcontrol 和 ngModel 之间创建一个钩子(Hook)。只有在我使用指令的位置旁边添加一个额外的隐藏输入时,在与 formGroup-tag 相同的组件中,它才有效。但这似乎有点多余。有没有更好的解决方案?

注意:将 FormControl 传递给指令并使用该表单控件属性的名称也不起作用。以自己的形式嵌套输入似乎并不比隐藏输入更冗长。

最佳答案

我通过将控件本身传递给指令并使用 [formControl]="control"将其连接到输入来解决它。

关于angular - 在新的 Angular 2 表单中将 NgModel 绑定(bind)到 FormControl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37994735/

相关文章:

javascript - 我如何在悬停时更改图像源并单击 Angular 2 其在 ngFor 生成的列表中

angular - 为什么 [myHighlight] ="..."对属性指令有效?

angular - 以 Angular 控制重置事件

css - 如果 mat-form-field 在组件中,则表单布局会中断

javascript - ngSwitch 是 "Attribute Directive"还是 "Structural Directive"?

angular - 从 NgForm 中检索 NgModel

Angular 2 使用 ngrx + RxJS 订阅多个组件/路由来填充存储

angular - 指示正在进行异步验证的类

angular - 在 Angular 2+ 中用微调器替换加载内容的指令

angular - 如何在 Angular2 中切换布局