Angular manually update ngModel and set form to dirty or invalid?
Why not use Reactive forms (FormGroup
),
let testForm = new FormGroup({
myText: new FormControl('initial value')
})
<form [formGroup]="testForm">
<input type="text" formControlName="myText">
</form>
<button (click)="updateMyTextModel()">Update myTextModel</button>
<div *ngIf="testForm.dirty">testForm diry</div>
<div *ngIf="testForm.touched">testForm touched</div>
In your function, you can use markAsDirty()
based on whatever condition you want.
updateMyTextModel(): void {
this.myTextModel = "updated model value";
if ( // some condition ) {
this.testForm.markAsDirty();
}
}
To set individual form controls as dirty/touched, you can use
this.testForm.get('myText').markAsDirty();
this.testForm.get('myText').markAsTouched();
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
This should work:
@ViewChild('testForm') testForm;
updateMyTextModel(): void {
this.myTextModel = "updated model value";
this.myForm.form.markAsDirty();
}