Angular手动更新ngModel并将表单设置为脏或无效?

Tob*_*oby 9 typescript angular angular4-forms

我有一个表单和这样的底层模型

来自组件

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

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>
Run Code Online (Sandbox Code Playgroud)

如何从代码中设置触摸或脏的表单?

注意:在此示例中,我使用按钮来触发模型更改,但我也可能以其他方式更新模型,例如在来自web api异步请求的回调中.

小智 12

解:

//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 {}
Run Code Online (Sandbox Code Playgroud)

Plunkr工作:

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


cyb*_*e92 6

为什么不使用反应式(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>
Run Code Online (Sandbox Code Playgroud)

在你的函数中,你可以markAsDirty()根据你想要的任何条件使用。

updateMyTextModel(): void {
    this.myTextModel = "updated model value";
    if ( // some condition ) {
        this.testForm.markAsDirty();
    }
}
Run Code Online (Sandbox Code Playgroud)

要将单个表单控件设置为脏/触摸,您可以使用

this.testForm.get('myText').markAsDirty();
this.testForm.get('myText').markAsTouched();
Run Code Online (Sandbox Code Playgroud)