M.Itani M.Itani - 10 months ago 32
HTML Question

Form Validation - Text being sent as 'Undefined' to API

I'm trying to send a textfield user input to a web api to validate it, however it's being sent as 'undefined' to my server

here is my code


<div class="form-group">
<!-- Rather than set an ngModel, we use the formControl directive to sync our input to the complexForm object. Notice that we are also setting the attribute we wish the corresponding input to sync with. We no longer need the name attribute, but can optionally add it. -->
<input class="form-control" type="text" [validator]="complexForm.controls['username']" [formControl]="complexForm.controls['username']" >

validator directive

import { Directive, ElementRef, HostListener, Input } from '@angular/core';
import { Http, Headers, Response, RequestOptions } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

selector: '[validator]'
export class ValidationDirective {
constructor(private el: ElementRef, private http: Http) { }

@Input('myUsername') username: string;

@HostListener('focusout') onFocusOut() {

private isAvailable(username: string) {
let url = 'myURL' + username;
let headers = new Headers();
headers.append('user', sessionStorage.getItem('username'));
headers.append('token', sessionStorage.getItem('token'));
headers.append('accesstime', sessionStorage.getItem('AccessTime'));

let options = new RequestOptions({ headers: headers });

this.http.get(url, options)
.subscribe((res: Response) => console.log(res.json()));


Why is the directive failing to take the input? and if it did, its sending the text input as 'undefined'. My aim is to send the username textfield when I focus out of the textfield to check if the username is taken. my Web API returns 'Y' or 'N' depending if the username is taken.

I'm very new to this, so I bet there would be some obvious mistakes.

thank you!

Answer Source

You are using validator both as directive name and input, then you should change your @Input part to

username: string;

Also, you are setting FormControl to directive validator's input(username), so use this.username.value to retrieve its value.

@HostListener('focusout') onFocusOut() {

Sample plunker demo.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download