微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

来自组件

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工作:

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐