1

My html code ::

<form novalidate [formGroup]="personForm" (ngSubmit)="onSubmit()" class="form-horizontal">
    <div class="form-group" [ngClass]="{'has-error':!personForm.controls.username.valid && personForm.controls.username.touched}">
            <div class="col-sm-6">
                <label class="control-label" for="username">Username</label><span>*</span>
                <input type="text" class="form-control" id="username" formControlName="username" />
            </div>
        </div>
        <div class="alert alert-danger" role="alert"
             *ngIf="!personForm.controls.username.valid && personForm.controls.username.touched">
            You must enter a username
        </div>
</form>

AND ts file :: [EDITED]

import { Component , OnInit } from '@angular/core';
import 'rxjs/Rx';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { HomeService } from './../Service/home.service'
import { User, Users } from '../Models/xyz'
import {Router} from '@angular/router'
@Component({
    templateUrl: './add.component.html',
    styleUrls:['./form.component.css'],
})

export class AddComponent implements OnInit {
    //users: IUser;
    personForm: FormGroup;
    successfulSave: boolean;
    errors: string[];
    afterAdded = false;
    currentUser: Users;
    timer: any;
    msg = "";

    pageTitle = 'Add User';

    constructor(private _homeService: HomeService, private _http: Http, private _router: Router, private fb: FormBuilder) {

        this.currentUser = new Users();
    }
    ngOnInit(): void{
        clearTimeout(this.timer);
        this.personForm = this.fb.group({
            username: ['', Validators.required],
            firstName: ['', Validators.required],
            lastname: ['', Validators.required],
            email: ['', Validators.required],
            password: ['', Validators.required],
            gender: ['', Validators.required]
        });
        this.errors = [];
    }


    onSubmit() {
        if (this.personForm.valid) {
            let headers = new Headers({ 'Content-Type': 'application/json' });
            let options = new RequestOptions({ headers: headers });
            let person = {
                username: this.personForm.value.username,
                firstName: this.personForm.value.firstname,
                lastname: this.personForm.value.lastname,
                email: this.personForm.value.email,
                password: this.personForm.value.password,
                gender: this.personForm.value.gender,
            };
            this.errors = [];
            this._http.post('/api/person', JSON.stringify(person), options)
                .map(res => res.json())
                .subscribe(
                (data) => this.successfulSave = true,
                (err) => {
                    this.successfulSave = false;
                    if (err.status === 400) {
                        // handle validation error
                        let validationErrorDictionary = JSON.parse(err.text());
                        for (var fieldName in validationErrorDictionary) {
                            if (validationErrorDictionary.hasOwnProperty(fieldName)) {
                                this.errors.push(validationErrorDictionary[fieldName]);
                            }
                        }
                    } else {
                        this.errors.push("something went wrong!");
                    }
                });
        }
    }
}

When I run my code, my console shows me this error::

ERROR TypeError: Cannot read property 'valid' of undefined at Object.View_AddComponent_0._co [as updateDirectives] (ng:///AppModule/AddComponent.ngfactory.js:391:69) at Object.debugUpdateDirectives [as updateDirectives]

I am doing server-side validation so I can't figure out what is wrong with this code ...

I am using this link as reference::http://www.carlrippon.com/?p=720

2
  • You need to import the form builder in order to access its Properties. Add import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms'; into your ts file. Commented Nov 28, 2017 at 11:32
  • I already did ! Commented Nov 28, 2017 at 11:33

1 Answer 1

1
[formGroup]="personForm" (ngSubmit)="onSubmit()"

is missing in your form

Sign up to request clarification or add additional context in comments.

14 Comments

This is in my form tag .. Sorry I forgot to paste it. Let me update my que.
change personForm.controls.username to personForm.controls['username'] and formControlName="username" to [formControl]="username"
ERROR Error: Cannot find control with unspecified name attribute <--- then this error comes and after click in text box valid of undefined error comes
is private fb: FormBuilder added in the constructor?
yes i did all the things which is used in reference link
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.