Angular Attribute Directive form input

I’m struggling to get @Directive to work as intended.

I would like the Attr Directive to be able to access the model.password in the directive constructor and set variable varpassword with the current password.

I would also like to be able to retrieve all other inputs within the form field, how would i go about this?

The documentation for a lot of this is not complete since being in Beta i know.

I’ve been trying to figure this out for days with limited success. I’ve removed the imports that i have tried to get it working on because i think I’m confused how to use them properly within the directive i have tried “NgModel, NgControl, ControlGroup, NgFormModel, FormBuilder…”.

My test example code below.


<form #testForm="ngForm">
    Email Address: 
    <input type="text" name="username" size="50" required="required" [(ngModel)]="model.username" ngControl="username" #username="ngForm" />

    <input type="password" name="password" size="20" required="required" [(ngModel)]="model.password" ngControl="password" #password="ngForm" testdir />

    <input type="submit" value="Login" />


import {Component} from 'angular2/core';

import {TestDirective} from '../../directives/test.directive';

    selector: 'test-app',
    templateUrl: 'login-form.html',
    directives: [TestDirective]
export class TestApp {}


import {Directive} from 'angular2/core';

    selector: '[testdir]',
    host: {
        '(keydown)': 'run()'
export class TestDirective {

    varpassword: string;

    constructor() {
        this.varpassword = [******]

    run() {
        console.log( this.varpassword );


If anyone can point me in the right direction would be much appreciated.

Leave a Reply

2 Comment threads
0 Thread replies
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
newest oldest most voted
Notify of

You need to inject NgControl into your directive:

export class TestDirective {
  varpassword: string;

  constructor(private ctrl:NgControl) {

  ngOnInit() {
    this.varpassword = this.ctrl.value;

Se this plunkr:


Example of input directive with commas when focus out. import {Directive, ElementRef} from '@angular/core'; @Directive({ selector: '[numberInput]', host: { '(focus)': '_onFocus()', '(blur)': '_onBlur()', '(keydown)': '_onKeypress($event)' } }) export class InputNumberDirective { inputElement: ElementRef; constructor(el: ElementRef) { this.inputElement = el; } _onBlur() { this.inputElement.nativeElement.value = this.inputElement.nativeElement.value.length > 0 ? parseInt(this.inputElement.nativeElement.value).toString().replace(/(d)(?=(ddd)+(?!d))/g, "$1,") : ''; } _onKeypress(event: KeyboardEvent) { if((event.which>= 58 && event.which<=126) || (event.keyCode >= 33 && event.which<= 47)){ event.preventDefault(); } return event; } }