加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 17:57:21 所属栏目:安全 来源:网络整理
导读:我有一个表单和这样的底层模型 来自组件 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=
我有一个表单和这样的底层模型

来自组件

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读