过formControlName语法创建的FormControl

过formControlName语法创建的FormControl

本文介绍了Angular2 v.2.3-让指令访问通过formControlName语法创建的FormControl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在尝试制定一个可以操纵FormControl的指令.

So I'm trying to make a directive that can manipulate a FormControl.

似乎,如果我改用长语法在模板中声明表单控件,则可以将控件传递给指令以直接@Input()绑定对其进行填充;即:使用以下模板:

It seems that if I use the long syntax for declaring form controls in the template instead, I can pass the control to a directive to do stuff with it as a direct @Input() bind; i.e.: With the following template:

<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语法,则:

But if I were using the formControlName syntax in the template instead:

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

我将如何在指令中引用(隐式?)制成的FormControl?

How would I reference the (implicitly?) made FormControl in the directive?

推荐答案

如果您使用NgControlElementRefHostListener和构造函数注入,我们可以有一个适用于或[formControl]伪装甚至是模板驱动的形式:

If you utilize NgControl, ElementRef, HostListener and constructor injection we can have a directive applicable to form controls from reactive forms in either formControlName or [formControl] guise and even template driven forms:

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);
  }
}

这是一个适用的演示

这篇关于Angular2 v.2.3-让指令访问通过formControlName语法创建的FormControl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 02:30