【问题标题】:Working with model-driven form and validation使用模型驱动的表单和验证
【发布时间】:2016-09-20 21:53:24
【问题描述】:

我有这样的表单控制:

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

由于[class.has-error]="!orderForm.controls.persons.controls[0].controls.firstName.valid &amp;&amp; orderForm.controls.persons.controls[0].controls.firstName.touched 太长,是否有更简单、更短的方法来设置 has-error 类?

组件定义如下:

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

【问题讨论】:

    标签: angular angular2-forms


    【解决方案1】:

    Angular2 自己添加了一些 CSS 类。您正在寻找的是 ng-invalid。如果在模型中连接到您的控件的验证器将返回 false,则将添加此类。您不需要使用自己的“has-error”类。

    【讨论】:

    • 嗨 Celebes,是的,我知道 angular 设置了 ng-valid、ng-invalid 类。关键是我正在使用引导程序进行样式设置,并且它需要具有错误类到表单组才能正确设置样式。
    • 请在问题中也发布您的组件代码。您应该能够将控件分配给变量并使用它们,例如:var firstNameControl = orderForm.controls.persons.controls[0].controls.firstName 然后使用firstNameControl .touched,但是您的执行链对我来说似乎很奇怪而且太长了。最好将整个逻辑封装在 [class.has-error]="firstNameHasError()" 之类的方法中
    猜你喜欢
    • 2016-09-11
    • 2016-08-08
    • 2017-03-18
    • 2018-05-31
    • 2017-09-17
    • 2017-02-06
    • 2017-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多