How to programmatically change pristine property in angular 2 form without ng-model

Oleksii picture Oleksii · May 10, 2016 · Viewed 7.2k times · Source

I'm new in Angular 2 framework. I appreciate any help.

I have usual component in angular 2:

import {FORM_DIRECTIVES, FormBuilder, Validators} from 'angular2/common';

export class TestComponent {
    public values = ['value1', 'value2', 'value3', 'value4'];
}

Then I'm injecting FormBuilder into the constructor function:

@Inject(FormBuilder) public fb

HTML contain next markup:

<input [(ngModel)]="formData.title" type="text" class="form-control" ngControl="title">

Title and description works great. But I've added bootstrap dropdown and it has no any form element.

<div *ngFor="#value of values" (click)="onValueChanged(value)" class="dropdown-item">{{value}}</div>

So, the problem is that html markup doesn't contain any model. The way I tried to solve this issue is to create function onValueChanged

 onValueChanged(value){
    this.formData.controls.value.updateValue(value);
    this.formData.value = value;
    console.log(this.formData.pristine) //Still true :(
}

Both of these line are not working, because this.formData.pristine is not changes after dropdown is changed.

For now I'm thinking how to update FormBuilder, it would be fine to have some methods, for example this.fb.update()

Answer

G&#252;nter Z&#246;chbauer picture Günter Zöchbauer · May 10, 2016

You can remove pristine status using

this.formData.controls.value.markAsDirty();

The current possibilities are quite limited. See also https://github.com/angular/angular/issues/4933