Search code examples
angulartypescriptangular4-forms

Angular manually update ngModel and set form to dirty or invalid?


I have a form and an underlying model like this

From component

myTextModel: string;
updateMyTextModel(): void {
    this.myTextModel = "updated model value";
    //todo- set form dirty (or invalid or touched) here
}

Html template

<form #testForm="ngForm" id="testForm">
  <input type="text" id="myText" [(ngModel)]="myTextModel" name="myText" #myText="ngModel">
</form>
<button (click)="updateMyTextModel()">Update myTextModel</button>
<div *ngIf="testForm.dirty">testForm diry</div>
<div *ngIf="testForm.touched">testForm touched</div>

How do I set the form touched or dirty from code?

Note: In this example i use a button to trigger the model change, but i also might update the model in other ways, such as in a callback from an web api async request.


Solution

  • Solution:

    //our root app component
    import {Component, NgModule, VERSION} from '@angular/core'
    import {BrowserModule} from '@angular/platform-browser'
    import { Component, ViewChild } from '@angular/core';
    import { FormsModule }   from '@angular/forms';
    
    @Component({
      selector: 'my-app',
      template: `
        <form #testForm="ngForm" id="testForm">
            <input type="text" id="myText" [(ngModel)]="myTextModel" name="myText" #myText="ngModel">
        </form>
        <button (click)="updateMyTextModel()">Update myTextModel</button>
        <div *ngIf="testForm.dirty">testForm diry</div>
        <div *ngIf="testForm.touched">testForm touched</div>
      `,
    })
    export class App {
    
      @ViewChild('testForm') test: any;
    
      updateMyTextModel(){
        this.test.control.markAsTouched();
        this.test.control.markAsDirty();
    
      }
    
      constructor() {
        console.log(this.test);
      }
    }
    
    @NgModule({
      imports: [ BrowserModule,FormsModule ],
      declarations: [ App ],
      bootstrap: [ App ]
    })
    export class AppModule {}
    

    Plunkr working:

    https://plnkr.co/edit/YthHCEp6iTfGPVcNr0JF?p=preview