Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: Cannot read property 'validator' of undefined

Ok so this is officially driving me mad now.

I have two components in my Angular 2 app at the moment, each including a form. The signup form is working fine, but I am having trouble with my signin form. Most recently I have been using the signup component as a template for the signin component, just to try and find the issue.

I have trimmed all but the most necessary code from both the component's class and the component's template. My component's template currently looks like this:

<link href="css/animation.css" rel="stylesheet">

<section id="signin_alt" class="authenty signin-alt">
    <form [ngFormModel]="signinForm" novalidate>
    </form>
</section>

My component's class looks like this:

import { Component } from 'angular2/core';
import { ControlGroup, FormBuilder, AbstractControl, Validators } from 'angular2/common';
import { RouterOutlet, RouterLink, RouteConfig, Router, ROUTER_DIRECTIVES } from 'angular2/router';
import { AuthenticationService } from './services/authentication.service';
import { AppComponent } from '../app.component';

@Component({
    selector: 'signin',
    directives: [RouterOutlet, RouterLink],
    template: require('./signin.component.html')
})
export class SigninComponent {
    signinForm: ControlGroup;
}

If I remove the [ngFormModel] from the form, it doesn't throw any errors. When I add the attribute, I get this delicious result:

EXCEPTION: TypeError: Cannot read property 'validator' of undefined in [signinForm in SigninComponent@3:14]

For the sake of completeness, here is my webpack config:

var sliceArgs = Function.prototype.call.bind(Array.prototype.slice);
var toString = Function.prototype.call.bind(Object.prototype.toString);
var path = require('path');
var webpack = require('webpack');

module.exports = {
    devtool: 'source-map',
    debug: true,
    devServer: {
        historyApiFallback: true,
        contentBase: 'src/public',
        publicPath: '/__build__'
    },
    entry: {
        'app': './src/app/bootstrap',
        'vendor': './src/app/vendor.ts'
    },
    output: {
        path: root('public/__build__'),
        filename: '[name].js',
        sourceMapFilename: '[name].js.map',
        chunkFilename: '[id].chunk.js'
    },
    resolve: {
        extensions: ['', '.ts', '.js', '.json', '.css', '.html']
    },
    module: {
        loaders: [
            { test: /\.json$/, loader: 'json' },
            { test: /\.css$/, loader: "style-loader!css-loader" },
            { test: /\.png$/, loader: "url-loader?limit=100000" },
            { test: /\.jpg$/, loader: "file-loader" },
            { test: /\.html$/, loader: 'html' },
            {
                test: /\.ts$/,
                loader: 'ts',
                exclude: [/\.spec\.ts$/, /\.e2e\.ts$/, /node_modules/]
            },
            {
                test: /\.scss$/,
                loaders: ['style', 'css?sourceMap', 'sass?sourceMap']
            },
            {
                test: /\.(woff|woff2)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                loader: "url-loader?limit=10000&minetype=application/font-woff"
            },
            {
                test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                loader: "file-loader"
            }
        ]
    },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: 'vendor.bundle.js' }),
        new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery" })
    ]
};

function root(args) {
    args = sliceArgs(arguments, 0);
    return path.join.apply(path, [__dirname].concat(args));
}

function rootNode(args) {
    args = sliceArgs(arguments, 0);
    return root.apply(path, ['node_modules'].concat(args));
}

Looking at the stack trace, it seems the form is not being instantiated. The error is thrown in this Angular function:

NgFormModel.prototype.ngOnChanges = function (changes) {
    if (collection_1.StringMapWrapper.contains(changes, "form")) {
        var sync = shared_1.composeValidators(this._validators);
        this.form.validator = validators_1.Validators.compose([this.form.validator, sync]);
        var async = shared_1.composeAsyncValidators(this._asyncValidators);
        this.form.asyncValidator = validators_1.Validators.composeAsync([this.form.asyncValidator, async]);
        this.form.updateValueAndValidity({ onlySelf: true, emitEvent: false });
    }
    this._updateDomValue();
};

where 'this.form' is null.

Can anyone shed light on this? I have exhausted my knowledge of Angular 2 looking for a solution!

Thanks.

like image 936
serlingpa Avatar asked Jan 13 '16 10:01

serlingpa


1 Answers

Do you instantiate the within the signinForm object in the SigninComponent component since you leverage the ngFormModel directive. Something like that (for example):

constructor(_builder:FormBuilder) {
  this.signinForm = _builder.group({
        login: ['', Validators.required],
        password: ['', Validators.required]
});

Hope it helps you, Thierry

like image 64
Thierry Templier Avatar answered Oct 15 '22 02:10

Thierry Templier