从Angular2中的原始元素获取表单控件

A. *_*uff 3 angular2-forms angular2-directives angular

假设我正在编写一个自定义属性指令,用于Angular2表单元素.我希望能够像我这样使用我的属性:

<form [formGroup]="myFormGroup">
  <input type="text" [myHighlight] formControlName="name" />
</form>
Run Code Online (Sandbox Code Playgroud)

在我的指令里面,我有这样的事情:

@Directive({selector: '[myHighlight]'})
export class MyHighlightDirective {
  constructor (private el: ElementRef) {
    this.el.nativeElement.style.backgroundColor = 'yellow';
  }
};
Run Code Online (Sandbox Code Playgroud)

但现在让我们说我想对输入控件的所有更改做些什么.也许我想在每次改变时随机化颜色.

当用户在输入框中键入时HostListener('onChange'),Angular2指南中的事件将起作用.但是对于setValue在窗体控件上调用的事件,它不会被激活,即使emitEvent设置为true也是如此.Form上的Angular文档说这setValue将导致valueChanges在窗体控件对象上发出事件.但是我不想每次使用它时都要将它传递给指令,因为那很笨重.

有没有其他方法可以让指令获得对原始表单控件的访问权限,因为它只有元素引用?

sno*_*ete 7

Angular DI来救援!

您可以使用Angular Dependency Injection系统注入附加到指令的host元素的FormControl.

@Directive({selector: '[myHighlight]'})
export class MyHighlightDirective {
  constructor (private el: ElementRef, private formControl: FormControl) {
    // have fun with formControl.valueChanges
    .......

  }
};
Run Code Online (Sandbox Code Playgroud)

为什么这样有效:

Angular将指令注册到附加指令的元素的注入器中.因此,当您要求特定指令的实例时,第一个查找将首先在主机元素上. (同样适用于组件)


Nav*_*raj 5

注入 NgControl,它是 FormControlName 的类型

import { NgControl } from '@angular/forms';

@Directive({selector: '[myHighlight]'})
export class MyHighlightDirective {
  constructor (private el: ElementRef, private formControl: NgControl) {
    this.el.nativeElement.style.backgroundColor = 'yellow';
    ....
    //listen to validation status
    this.formControl.statusChanges.subscribe((state)=>{
       ...
    });
  }
};
Run Code Online (Sandbox Code Playgroud)