Angular.js programmatically setting a form field to dirty

后端 未结 11 2042
孤独总比滥情好
孤独总比滥情好 2020-12-02 10:57

I am programmatically updating some of the fields on my form with a value and I would like to set the field state to $dirty. Doing something like:

11条回答
  •  天命终不由人
    2020-12-02 11:32

    Angular 2

    For anyone looking to do the same in Angular 2 it is very similar apart from getting a hold of the form

    Name is required

    import { Component, } from '@angular/core';
    import { FormBuilder, Validators } from '@angular/common';
    
    @Component({
        selector: 'my-example-form',
        templateUrl: 'app/my-example-form.component.html',
        directives: []
    })
    export class MyFormComponent {
        myFormModel: any;
    
        constructor(private _formBuilder: FormBuilder) {
            this.myFormModel = this._formBuilder.group({
                'username': ['', Validators.required],
                'password': ['', Validators.required]
            });
        }
    
        onSubmit() {
            this.myFormModel.markAsDirty();
            for (let control in this.myFormModel.controls) {
                this.myFormModel.controls[control].markAsDirty();
            };
    
            if (this.myFormModel.dirty && this.myFormModel.valid) {
                // My submit logic
            }
        }
    }
    

提交回复
热议问题