如何在没有 ng-model 的情况下以 angular 2 形式以编程方式更改原始属性 [英] How to programmatically change pristine property in angular 2 form without ng-model

查看:23
本文介绍了如何在没有 ng-model 的情况下以 angular 2 形式以编程方式更改原始属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Angular 2 框架的新手.感谢您的帮助.

我在 angular 2 中有常用组件:

import {FORM_DIRECTIVES, FormBuilder, Validators} from 'angular2/common';导出类 TestComponent {公共值 = ['value1', 'value2', 'value3', 'value4'];}

然后我将 FormBuilder 注入到构造函数中:

@Inject(FormBuilder) 公共 fb

HTML 包含下一个标记:

标题和描述效果很好.但是我添加了引导程序下拉菜单并且它没有任何表单元素.

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

所以,问题是 html 标记不包含任何模型.我试图解决这个问题的方法是创建函数 onValueChanged

 onValueChanged(value){this.formData.controls.value.updateValue(value);this.formData.value = 值;console.log(this.formData.pristine)//还是真的 :(}

这两行都不起作用,因为 this.formData.pristine 在下拉列表更改后不会更改.

现在我正在考虑如何更新FormBuilder,最好有一些方法,例如this.fb.update()

解决方案

You can remove pristine status using

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

目前的可能性非常有限.另见 https://github.com/angular/angular/issues/4933>

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

解决方案

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

这篇关于如何在没有 ng-model 的情况下以 angular 2 形式以编程方式更改原始属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆