Angular 2:无法读取undefined的属性'validator'

时间:2016-01-13 10:51:26

标签: angular webpack

好的,所以这正在让我疯狂。

目前我的Angular 2应用程序中有两个组件,每个组件都包含一个表单。注册表格工作正常,但我的登录表格有问题。最近我一直使用注册组件作为signin组件的模板,只是为了尝试找到问题。

我已经从组件的类和组件的模板中删除了除了最必要的代码之外的所有代码。我的组件模板目前看起来像这样:

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

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

我的组件类看起来像这样:

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;
}

如果我从表单中删除[ngFormModel],它不会抛出任何错误。当我添加属性时,我得到了这个美味的结果:

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

为了完整起见,这是我的webpack配置:

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));
}

查看堆栈跟踪,似乎表单未实例化。此Angular函数抛出错误:

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();
};

其中'this.form'为空。

任何人都可以对此有所了解吗?我已经用尽了我对Angular 2寻求解决方案的了解!

感谢。

1 个答案:

答案 0 :(得分:11)

自从利用signinForm指令以来,您是否在SigninComponent组件中的ngFormModel对象中进行实例化。这样的东西(例如):

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

希望它可以帮到你, 亨利