7

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()

garethdn
  • 12,022
  • 11
  • 49
  • 83
Oleksii
  • 328
  • 3
  • 17

1 Answers1

14

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

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • If this answers your question please accept the answer to indicate the problem is solved. If you want to wait for alternative answers you don't need to accept it though. You can also make another answer the accepted answer at any time. – Günter Zöchbauer May 10 '16 at 11:46
  • 2
    @GünterZöchbauer how to do the same in template driven forms? If I have the form declared like `#myForm="ngForm" ` and accessing `myForm.form.controls.value` in a function gives `undefined` ! – yashhy Dec 22 '16 at 07:53
  • 1
    You also need `@ViewChild('myForm') myForm;` to be able to access the form from the components code. `myForm` won't be set when the constuctor is executed. Besides that, you can use `this.myForm.get('controlName')....` – Günter Zöchbauer Dec 22 '16 at 07:58