Angular2 v.2.3 - 让指令访问通过 formControlName 语法创建的 FormControl

标签 angular angular2-forms

所以我正在尝试制作一个可以操作 FormControl 的指令。

似乎如果我改用长语法在模板中声明表单控件,我可以将控件传递给一个指令来用它做一些事情作为直接@Input() 绑定(bind);即:使用以下模板:

<form [formGroup]="myForm">
    <input type="text" id="myText" [formControl]="myForm.controls['myText']" my-directive>
</form>

以及以下组件逻辑:

@Component({
    // Properties go here.
})
class MyComponent {
    myForm: FormGroup;

    constructor(fb: FormBuilder) {
        // Constructor logic...
    }

    ngOnInit() {
        this.myForm = this.fb.group({
            "myText": [""]
        });
    }
}

指令看起来像:

@Directive({
    selector: "[my-directive]"
})
class MyDirective {
    Input() formControl: FormControl;
}

但是如果我在模板中使用 formControlName 语法:

<form [formGroup]="myForm">
    <input type="text" id="myText" formControlName="myText" my-directive>
</form>

我如何在指令中引用(隐含地?)made FormControl?

最佳答案

如果您使用 NgControlElementRefHostListener 和构造函数注入(inject),我们可以在 formControlName[formControl] 伪装甚至模板驱动的表单:

import { Directive, ElementRef, HostListener } from "@angular/core";
import { NgControl } from "@angular/forms";

@Directive({
  selector: '[my-directive]'
})
export class MyDirective {
  constructor(private el: ElementRef, private control : NgControl) { }

  @HostListener('input',['$event']) onEvent($event){
    let valueToTransform = this.el.nativeElement.value;
    // do something with the valueToTransform
    this.control.control.setValue(valueToTransform);
  }
}

这是一个 applicable demo

关于Angular2 v.2.3 - 让指令访问通过 formControlName 语法创建的 FormControl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41171686/

相关文章:

Angular2 自定义表单控件,包括文本字段和错误消息

跨组件分布的 Angular 2 形式

angular - Angular cli 中的未知选项 -m

angular - View 不会刷新收到的IPC消息

css - ionic 3 动态主题化应用程序

angular2 在特定元素上手动触发点击事件

css - 在CSS中选择angular2元素

javascript - angular - 基于 mat-select 选项的条件元素

angular - 在 Angular 4 Dart 中获取 ComponentFactory 的最佳方法是什么?

javascript - Angular2中如何订阅表单组中仅一个键的变化