标签: angular2-forms

设置值的方法和更新表单控件的有效性

我想知道是否有任何方法来设置值并更新表单控件的有效性.鉴于以下内容:

this.updateForm = this._formBuilder.group({
    user: ['',Validators.required]     
});
Run Code Online (Sandbox Code Playgroud)

我有一些关于更改触发器的指令,触发以下内容:

changeUserSelection(value){
    this.updateForm.controls['user'].value = value // doesnt trigger validation?
}
Run Code Online (Sandbox Code Playgroud)

我想知道如何设置值,并触发此字段的验证.按照我的方式这样做,不会触发验证.

谢谢

angular2-forms angular

4
推荐指数
3
解决办法
2万
查看次数

如何获取angular2 formcontrol父级

如何在控件的嵌套表单组中获取父表单组。在验证控件时,我需要一个同级控件值。这两个控件都是formgroup的一部分,而formgroup是formArray的一部分。我知道我们有root,它提供了root元素。如何获得给定表单控件的直接父级。

angular2-forms angular

4
推荐指数
1
解决办法
5841
查看次数

使用Angular 2 Forms动态标记字段的正确方法是什么?

使用Angular 2(2.0.0),使用Angular Forms 动态标记字段的建议方法是什么?

在他们的所有示例中,只添加了必需的属性,如:

<input type="text" class="form-control" id="name" required>
Run Code Online (Sandbox Code Playgroud)

如果我绑定的模型有一个IsRequired属性,那将是真/假?

如果我使用类似的东西:

<input [(ngModel)]="field.Value" type="text" value="{{field.Value}}" [attr.required]="field.IsRequired"/>
Run Code Online (Sandbox Code Playgroud)

这在页面上呈现(注意="true"):

<input type="text" required="true" />
Run Code Online (Sandbox Code Playgroud)

出于某种原因,当Angular具有实际值(="true")时,它似乎不会识别此属性,所以当此字段为空时,我的表单本身仍然有效:

<form class="ng-untouched ng-pristine ng-valid">
Run Code Online (Sandbox Code Playgroud)

所以看起来我必须使用required而不是required="true",但是如何动态添加该属性?

什么也行不通:

<input type="text" {{ getRequiredAttr(field) }} />
Run Code Online (Sandbox Code Playgroud)

以为我可能有一个函数可以根据字段返回我的字符串"required",这只会产生模板错误.

有没有办法完成这个并只required为我的属性渲染?还是一种让Angular在值为true/false时识别此属性的方法?

FWIW - 我已经验证我可以根据我的属性*ngIf编写两个几乎相同的<input type='text' />控件,IsRequired并使用required属性对其进行硬编码,但这看起来很糟糕.希望有更好的方法!

html5-validation angular2-forms angular

4
推荐指数
2
解决办法
6726
查看次数

Angular 2 - Checkbox未保持同步

我正在研究Angular 2.0(是的,有点落后于当前的2.4).

我有一个复选框列表.我试图在未检查到最后的复选框时检查所有的复选框.

HTML

<div *ngFor="let filter of filters">
    <label htmlFor="check-box-{{filter.text}}"
           [ngClass]="(filter.selected)? 'active' : '' ">

           <input type="checkbox" 
                 name="check-box-{{filter.text}}"
                 [checked]="filter.selected"
                 (change)="onSelectFilter(filter)"
                 attr.id="check-box-{{filter.text}}">

           {{filter.selected}} -  ({{filter.counter}})

    </label>
</div>
Run Code Online (Sandbox Code Playgroud)

TS

onSelectFilter(filter: Filter){
    filter.toggleSelection();


    let isAnyFilterSelected = this.filters.find(filter => filter.selected);

    // If no filter is selected then ALL filters are selected
    if(!isAnyFilterSelected){
        this.filters.forEach(filter => filter.selected = true );
    }

}
Run Code Online (Sandbox Code Playgroud)

我为它创造了一个plunker.

https://plnkr.co/edit/uzF6Lk5fxRZjXBOaS9ob?p=preview

如果取消选中CHECKED属性为TRUE的唯一复选框,我希望所有复选框都具有CHECKED属性.这不会发生.

在此输入图像描述

有任何想法吗?

checkbox angular2-forms angular

4
推荐指数
1
解决办法
5036
查看次数

角形式 - 访问模板中的嵌套控件

我的表单中有一个嵌套控件组,我想访问它们的表单状态值(如pristine和valid)以动态显示验证错误.

这是动态构建的

controlMap['password'] = this.password;
controlMap['customData'] = this.formBuilder.group(customDataControlMap);
this.form = new FormGroup(controlMap)
Run Code Online (Sandbox Code Playgroud)

来自obj就像

{
  controls:{
    password:{} 
    --->nested 
    customData:{
       controls:{
          customerId:{}
       }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

模板中的ngClass看起来很难看

[ngClass]="( !form.controls.customData.controls.customerId.valid && !form.controls.customData.controls.customerId.touched && submitted) ? 'invalid' : ''"
Run Code Online (Sandbox Code Playgroud)

当我尝试构建它时,它将无法工作(ng build --prod)

错误在ng:///Users/hanche/Desktop/Development/selfbits/beratergruppe-leistungen-webclient/src/app/pages/clients/client-new/client-new.component.html(6,61):属性y "AbstractControl"类型中不存在"controls".

angular2-forms angular

4
推荐指数
1
解决办法
2808
查看次数

patch使用angular2在嵌套表单控件中的值

我需要在FormBuiler中的嵌套控件中设置一个值,模型如下:

this.addAccForm = this.fb.group({
      accid: ['', Validators.required],
      status: '',
      cyc: this.fb.array([
        this.initCyc(),
      ])
    })

initCyc() {
      return this.fb.group({
        cycid: ['', Validators.required],
        name: ['', Validators.required],
        description: ['', Validators.required],
        status: ['', Validators.required],
        det: this.fb.group({
            dcycid: ['', Validators.required],
            status: ['', Validators.required]
        })
      })
Run Code Online (Sandbox Code Playgroud)

我需要设置一个值cycid和dcycid但我坚持它,我试图使用以下行,但它没有帮助:

this.addAccForm.patchValue({cyc: { [0]: {cycid: 1234567 }}});
Run Code Online (Sandbox Code Playgroud)

//

this.addAccForm.patchValue({cyc: { [0]: { det : {dcycid: 9876543}}}});
Run Code Online (Sandbox Code Playgroud)

知道它应该怎么样?

angular2-forms angular2-formbuilder

4
推荐指数
4
解决办法
6698
查看次数

添加Moment JS的日子

添加几天到时刻js对象时遇到问题:

我正在使用此代码:

var contractMoment = this.moment(contract,'DD/MM/YYYY')
var start = contractMoment;
var end = contractMoment;

start = contractMoment.add(19, 'days');
end = contractMoment.add(51, 'days');
Run Code Online (Sandbox Code Playgroud)

在添加之前,contractMoment看起来像这样:

Thu Dec 02 2004 00:00:00 GMT-0600 (Central Standard Time)
Run Code Online (Sandbox Code Playgroud)

在我执行添加和控制台日志的开始和结束之后,这是我得到的:

Thu Dec 02 2004 00:00:00 GMT-0600 (Central Standard Time)
Run Code Online (Sandbox Code Playgroud)

它为每个返回一个时刻对象,我在这里缺少什么?添加的日期是埋藏在当下物体的某个地方吗?

momentjs typescript angular2-forms

4
推荐指数
1
解决办法
6855
查看次数

如何使用http.post上传文件和表单数据

我正在提交一个包含字段titledescription使用的表单,http.post它工作正常.我还允许用户使用相机拍摄照片并将其保存为base64格式的字符串.我需要通过相同的POST请求将此照片提交给服务器.我怎样才能做到这一点?到目前为止,我的代码如下所示,服务器在名为"photo"的字段中查找上传的照片:

headers = new Headers({'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'});
options = new RequestOptions({ headers: this.headers });

let data = {
  title: item.title,
  description: item.description
};

let params = new URLSearchParams();
for(let key in data){
    params.set(key, data[key]) 
}

this.http.post('http://example.com/items', params.toString(), this.options).subscribe(
  (result) => {
    console.log("success!");
  },
  (err) => {
    console.log(JSON.stringify(err));
  }
);
Run Code Online (Sandbox Code Playgroud)

ionic-framework angular-file-upload ionic2 angular2-forms

4
推荐指数
1
解决办法
6193
查看次数

为什么在我的测试中ngForm"控制"属性是空的?(角)

我有一个采用模板驱动形式的组件

<form (ngSubmit)="onSearchCorpus(form)" #form="ngForm">
<combo-box [(ngModel)]="model.corpus" name="corpus" #corpus="ngModel"></combo-box>
<input [(ngModel)]="model.label" name="label" id="label" type="text" required pattern="^(?!\s*$)[\w\_\-\:\s]*" maxlength="50" class="form-control label-name" autocomplete="off" #label="ngModel">
<textarea [(ngModel)]="model.query" name="query" id="query" maxlength="3600" required validateQuerySyntax class="form-control search-query" #query="ngModel" #queryControl
        placeholder="Example: (&quot;grantee&quot; OR &quot;grant&quot; OR &quot;sponsor&quot; OR &quot;contribute&quot; OR &quot;contributor&quot;) NEAR (&quot;non-profit organization&quot; OR &quot;charities&quot;)">
      </textarea>
 <button [disabled]="corpusValidationInProgress" type="submit" class="button-level-one">Search</button>
</form>
Run Code Online (Sandbox Code Playgroud)

在处理表单提交的方法中,我访问控制 NgForm实例的属性,它在浏览器中工作正常.

onSearchCorpus(formData: NgForm) {
   ...
   const corpusErrors = formData.controls.corpus.errors;
   ...
}
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试使用Karma测试此方法时,NgForm的controls属性为空.我很困惑为什么会这样.该方法失败并出错cannot read property "errors" of undefined.

以下是我的测试结果:

it('should not perform corpusSearch …
Run Code Online (Sandbox Code Playgroud)

javascript unit-testing angular2-forms angular2-testing angular

4
推荐指数
1
解决办法
1252
查看次数

Angular 2+材料垫-芯片列表formArray验证

如何验证mat-chip已将添加到中mat-chip-list。我正在使用ReactiveForms。我已经尝试过required验证器。

该值可以是名称列表,因此在提交表单之前,我需要确保名称列表中至少有1个名称。如果列表为空,mat-error则应显示错误消息。使用required验证器会使表单无效,而不管在列表中添加名称如何。

编辑:反应形式

我试图做一个自定义验证器,现在使用的是反应式表单,而不是模板驱动的表单,但是我无法使它正常工作。我编辑了以下代码以反映我的更改,并创建了此https://stackblitz.com/edit/angular-4d5vfj

的HTML

<form [formGroup]="myForm">
  <mat-form-field class="example-chip-list">
    <mat-chip-list #chipList formArrayName="names">
      <mat-chip *ngFor="let name of myForm.get('names').controls; let i=index;"
        [formGroupName]="i"
        [selectable]="selectable"
        [removable]="removable"
        (removed)="remove(myForm, i)">
        <mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
      </mat-chip>

       <input placeholder="Names"
          [matChipInputFor]="chipList"
          [matChipInputSeparatorKeyCodes]="separatorKeysCodes"
          [matChipInputAddOnBlur]="addOnBlur"
          (matChipInputTokenEnd)="add($event, asset)">
    </mat-chip-list>
    <mat-error>Atleast 1 name need to be added</mat-error>
  </mat-form-field>
</form>
Run Code Online (Sandbox Code Playgroud)

TS

import {COMMA, ENTER} from '@angular/cdk/keycodes';
import {Component} from '@angular/core';
import {FormGroup, FormControl, FormBuilder, FormArray} from '@angular/forms';
import {MatChipInputEvent} from '@angular/material';

@Component({
  selector: 'chip-list-validation-example', …
Run Code Online (Sandbox Code Playgroud)

angular2-forms angular-material2 angular angular-reactive-forms

4
推荐指数
2
解决办法
3285
查看次数