使用模型驱动的表单和验证

时间:2016-09-20 13:31:48

标签: angular angular2-forms

我正在进行这样的表单控件:

<div class="form-group" [class.has-error]="!orderForm.controls.persons.controls[0].controls.firstName.valid && orderForm.controls.persons.controls[0].controls.firstName.touched" [formGroupName]="0">
        <label class="control-label">First Name</label>
        <input type="text" class="form-control" formControlName="firstName" required />
</div>

是否有更容易和更短的方法来设置has-error类,因为[class.has-error]="!orderForm.controls.persons.controls[0].controls.firstName.valid && orderForm.controls.persons.controls[0].controls.firstName.touched太长了?

组件的定义如下:

   @Component({
        moduleId: module.id,
        selector: 'order-form',
        templateUrl: 'order-form.component.html'
    })
    export class OrderFormComponent implements OnInit {
        orderForm: FormGroup;
        visitorsType: FormControl;
        startDate: FormControl;
        endDate: FormControl;
        persons: FormArray;
        duration: FormControl;
...

表单初始化是这样的:

    ...
    constructor(private _quotesService: QuotesService, 
                private _formBuilder: FormBuilder) { }

    ngOnInit() {

            this.persons = this._formBuilder.array([]);

            this.orderForm = this._formBuilder.group({
                persons: this.persons,
            });

            (<FormArray>this.orderForm.controls['persons']).push(this.initVisitor(this.startDate.value));

            this.activate();
    }
    ...

1 个答案:

答案 0 :(得分:2)

Angular2自己添加了一些CSS类。你要找的那个是无效的。如果连接到模型中的Control的验证器将返回false,则将添加此类。您不需要使用自己的“has-error”类。