How to send input value to user directive in angular -2?

I am experimenting with custom angular -2 basic directives, where I want to parse the input value in my custom directive.

Let's get a look.

I have an application component called app.component.ts. Where did I get the input field.

<input [(ngModel)] = "myInput"/> 

Next I create a custom directive name custom.directive.ts

import { Directive, ElementRef, Renderer} from '@angular/core';

@Directive ({
  selector : '[customDir]'
})
export class CustomDirective{
  constructor(private el : ElementRef, private renderer: Renderer){ }
}

Now I would like to enter something in "app.component.ts" and analyze it in my custom directive, with which I can simply print it in the console.

Lets change my code ...

<app.component.ts>
<input [(ngModel)] = "myInput" [customDir] = "myInput"/> 
<custom.directive.ts>
import { Directive, ElementRef, Renderer, Input} from '@angular/core';

@Directive ({
  selector : '[customDir]'
})

export class CustomDirective{
  @Input('customDir') myInput : any;
  constructor(private el : ElementRef, private renderer: Renderer){ }
     console.log(this.myInput);
  }

But it does not work properly. Print un define ..

My concern is ...

1 ... How do I analyze data against every keystroke ..?

Please suggest me someone ...

+4
1
@Directive ({
  selector : '[customDir]',
  exportAs: 'customDir' // <<<=== added
})
export class CustomDirective{
  myInput : any;
}

<input customDir #customDir="customDir" [(ngModel)]="myInputInApp" (ngModelChange)="customDir.myInput = $event"/> 

customDir .

#customDir="customDir" , ( exportAs)

[(ngModel)]="customDir.myInput" , #customDir input. @Input() , Angular, .

:

@Directive ({
  selector : '[customDir]',
})
export class CustomDirective{

  @HostListener('ngModelChange', ['$event'])
  onModelChange(event) {
    console.log(event);
  }
}
<input customDir [(ngModel)]="someOtherProp"/> 

+3

Source: https://habr.com/ru/post/1659793/


All Articles