我有一个表单和这样的底层模型
来自组件
myTextModel: string; updateMyTextModel(): void { this.myTextModel = "updated model value"; //todo- set form dirty (or invalid or touched) here }
Html模板
<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>
如何从代码中设置触摸或脏的表单?
注意:在此示例中,我使用按钮来触发模型更改,但我也可能以其他方式更新模型,例如在来自web api异步请求的回调中.
解决方法
解:
//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工作: