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

大兔子大兔子 提交于 2019-12-22 07:56:11

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/37132541/how-to-programmatically-change-pristine-property-in-angular-2-form-without-ng-mo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!