How can I correctly identify / view the "dirty status" of angular2 -form?

I have a form in Angular2 (for example)

<form id="myLovelyForm" name="myLovelyForm" #myLovelyForm="ngForm"> <label [attr.for]="myLovelyCheckbox"> <input [attr.id]="myLovelyCheckbox" type="checkbox" [(ngModel)]="myLovelyCheckbox"> <span class="myLovelyCheckbox">myLovelyCheckbox</span> </label> </form> 

and the animation that should start if the form is dirty:

 <div id="myLovelyNotification" class="myLovelyNotification" [@notification]="myLovelyForm.form.dirty"> ..... ..... </div> 

The animation works correctly if I set [@notification] = true, but my myLovelyForm.dirty does not work if I touch the form and change the element.

If the @notification value is false, the animation stops, i.e. if the checkbox was selected earlier, and I cancel it by mistake and select it again, the form is not untouched (touched), but not dirty, so the animation should stop. If I manually set @notification = false, it works correctly.

The big question is: how can I correctly identify / view the "dirty status" of an angular2 form?

+5
source share
2 answers

You can subscribe to form changes:

 this.physicalForm.valueChanges .map((value) => { return value; }) .subscribe((value) => { if(this.selectedPhysical.weight != this.physicalForm.value.weight) { this.selectedPhysical.weight = this.physicalForm.value.weight; } this.isDirty == this.physicalForm.touched; }); 

If this event fires, then you know that your form is dirty.

this is an example of my actual application (the .abbr nut is the name of the form):

 ngOnInit() { for (let nut of this.userSettings.nutrientData) { this.foodSettingsForm.controls[nut.abbr].valueChanges .subscribe(v => { console.log("value: ", v); this.completeValueChange(nut.abbr, v); }); } } completeValueChange(field: string, value: boolean) { this.isChanged = true; Nutrient.updateNutrient(field, value, this.userSettings.nutrientData); } 
+2
source

Just -

 @ViewChild('f') templateForm: any; ngOnInit() { this.templateForm.valueChanges.subscribe((value: any) => { if (this.templateForm.dirty) { console.log('template form dirty - yes: ', value); } else { console.log('template form dirty - no: '); } }); } 

Where is your template located:

  <form #f="ngForm" (ngSubmit)="save(f)> ... </form> 

However, it still uses the template forms that really exist to help bridge the gap with Angular1 applications. The Driven Forms Model is an Angular 2 way to do this for anything but real core applications. See for example:

+3
source

All Articles