Angular 2表单控件未定义

时间:2016-11-17 06:54:28

标签: angular angular2-forms

我有一个带有一些控件的表单的角度2组件,在我的html中,我使用"类别"的有效属性。控制并抱怨:

  

无法阅读属性'有效'未定义的

这行HTML代码:[ngClass]="{'no-error': addForm.controls.categories.valid ||

组件类:

export class AddFormComponent implements OnInit {

  private addForm: FormGroup;
  private mealSelected: boolean;

    constructor(
        private formBuilder: FormBuilder,
        el: ElementRef) { }

    ngOnInit() {
        this.addForm = this.formBuilder.group({
            categories: [null, Validators.required],
            mealTypes: [[], this.mealTypesValidator()],
            brand: [null, Validators.required],
            name: [null, Validators.required],
            description: [null, Validators.required],
      image: null,
            webUrl: null,
        });
    }...

组件html:

    <small 
        [ngClass]="{'no-error': addForm.controls.categories.valid || 
        (addForm.controls.categories.pristine && !submitted)}" 
        class="text-danger">Please select at least 1 category.
    </small>

所以它说addForm.controls.categories没有定义。当我在addForm.controls.categories中定义ngOnInit时,怎么会这样?可能有一些显而易见的事情,我发现它太慢了。

编辑:等等,忘记加上上面的html在这里:

<form class="text-uppercase" (ngSubmit)="onSubmit()" #addForm="ngForm">

2 个答案:

答案 0 :(得分:2)

您需要输入FormControl

import { FormControl } from '@angular/forms';

答案 1 :(得分:1)

更改表单标记HTML,如下所示:

<form class="text-uppercase" (ngSubmit)="onSubmit()" [formGroup]="addForm">

正如您已将addForm声明为FormGroup,您必须使用FormGroupDirective表格而不是&#39; ngForm&#39;