Reputation: 2465
I am working on an Angular2 with Typescript project. I am trying to make a validation directive so I can send the value from the Html tag with the type of the input and response with a boolean value.
the directive I wrote is:
import { Directive, ElementRef, HostListener, Input, Output } from '@angular/core';
@Directive({
selector: '[validate]'
})
export class Validation{
@Input('validate') validateType: string;
@Input() validateValue: string;
@Output() status:boolean;
constructor(private el : ElementRef){
}
@HostListener('keyup') OnKeyUp(){
if(this.validateType === "number")
{
var isNumeric = /^[-+]?(\d+|\d+\.\d*|\d*\.\d+)$/;
this.status = isNumeric.test(this.validateValue);
}
}
}
and I register it in the app.module.ts:
import { Validation} from './validation-directive/validation.directive';
.
.
.
@NgModule({
.
.,
declarations: [
Validation
],
})
and the html code is:
<input #validateNumber [validate]="number" validationValue="validateNumber.value" />
<span>result is: </span>
I want the value to be passed from the input to the directive and the output would be shown up in the span.
the code is not working and the directive is not working, although it does not give an error. why? what is wrong with my code?
and how can I expose the output in the result span?
thank you
Upvotes: 1
Views: 1680
Reputation: 37403
See it on plunker
use exportAs
to access your directive properties in your template
html:
<input validate="number" #validator="validator" />
<span>result is: {{ validator.status }}</span>
ts:
import { Directive,Input,ElementRef,HostListener} from '@angular/core';
@Directive({
selector: '[validate]',
exportAs: "validator"
})
export class Validation{
@Input('validate') validateType: string;
status : boolean;
constructor(private el : ElementRef){
}
@HostListener('keyup') OnKeyUp(){
if(this.validateType === "number")
{
let value = this.el.nativeElement.value;
let isNumeric = /^[-+]?(\d+|\d+\.\d*|\d*\.\d+)$/;
this.status = isNumeric.test(value);
}
}
}
Upvotes: 2