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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47589101/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:05:20  来源:igfitidea点击:

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

angulartypescriptangular4-forms

提问by Toby

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

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>

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.

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

回答by Daniel Segura Pérez

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:

Plunkr 工作:

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

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

回答by cyberpirate92

Why not use Reactive forms (FormGroup),

为什么不使用反应式(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.

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

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();

回答by Riscie

This should work:

这应该有效:

@ViewChild('testForm') testForm;


updateMyTextModel(): void {
    this.myTextModel = "updated model value";
    this.myForm.form.markAsDirty();
}

回答by Sujay U N

If u need to loop through all input fields in a form and mark them touched or dirty :

如果您需要遍历表单中的所有输入字段并将它们标记为已触摸或脏的:

onSubmit(nameForm)
{
    let inputAryVar = nameForm.form.controls
    for(let keyVar in inputAryVar)
    {
        inputAryVar[keyVar].markAsTouched();
        inputAryVar[keyVar].markAsDirty();
    }
}

回答by Kurkov Igor

if you use NgFormform ref through something like this -

如果您NgForm通过这样的方式使用表单引用 -

@ViewChild('viewChildForm') public viewChildForm: NgForm;and try change form programmatically in .tsfile:

@ViewChild('viewChildForm') public viewChildForm: NgForm;并尝试在.ts文件中以编程方式更改表单:

  • To set form as invalid: this.viewChildForm.form.setErrors({ 'invalid': true });.

  • To set from as valid: this.viewChildForm.form.setErrors(null);

  • 将表单设置为无效:this.viewChildForm.form.setErrors({ 'invalid': true });

  • 将 from 设置为有效: this.viewChildForm.form.setErrors(null);