2017-12-01 5 views
0

は、私は、フォームとコードからの根本的な角度は手動で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の非同期要求からのコールバックなど、他の方法でモデルを更新することもできます。これは動作するはず

答えて

0

:あなたの関数では、反応性フォーム(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> 

を使用しないのはなぜ

@ViewChild('testForm') testForm; 


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

感謝を!よくやった! – Toby

0

を、あなたが好きな条件に基づいてmarkAsDirty()を使用することができます。作業

//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:

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

あなたは

this.testForm.get('myText').markAsDirty(); 
this.testForm.get('myText').markAsTouched(); 
+0

これを試してみてください、ありがとうございました:) – Toby

関連する問題