标签: angular-reactive-forms

Angular2反应形式显示基于验证失败条件的错误消息

我想提一下,我使用单独的通用组件,以显示错误,所以我不是直接将它们放在html中以避免重复,所以我不能直接在模板中链接和硬编码条件.

我有这个字段和两个验证:

this.username = new FormControl('', [ Validators.minLength(5), Validators.required ]); 
Run Code Online (Sandbox Code Playgroud)

如何为每个验证显示验证错误消息?假设我想在提交字段中显示任何内容时显示两个错误:
"最小长度为5"
"字段是必需的"

然后,如果你把东西放进去,它应该只显示:
"最小长度为5"

这是一个例子,但是,我的现实生活中的例子,比较两个电子邮件字段,如果它们是相同的,因此,如果邮件是不正确的是应该显示:
"电子邮件是不正确的"
"电子邮件是不一样的第一封电子邮件场"

因此,如果电子邮件是正确的并且电子邮件不相同,则只应显示:
"电子邮件与第一个电子邮件字段不同"

我如果没有通过验证的工作,但我不知道如何分开显示,如果一个验证通过,另一个没有,因为我要好好追加的真正原因失败的原因,而不是把两者一些通用的原因.

完整示例:

错误显示组件:

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-field-error-display',
  templateUrl: './field.error.display.component.html',
  styleUrls: ['./field.error.display.component.css']
})
export class FieldErrorDisplayComponent
{
    @Input() errorMsg: string;
    @Input() displayError: boolean;
}
Run Code Online (Sandbox Code Playgroud)

组件html:

<div *ngIf="displayError" >
  <small>{{errorMsg}}</small>
</div>
Run Code Online (Sandbox Code Playgroud)

在Register.html中使用erorr显示:

<form [formGroup]="_form" (ngSubmit)="register()">
<h4>Create a new account</h4>
<div class="form-group">
  <label for="email">Email Address</label>
  <input class="form-control" name="email" formControlName="email" />
  <app-field-error-display [displayError]="formValidationService.IsFieldValid(_form,'email')" errorMsg="Please insert correct email"></app-field-error-display> …
Run Code Online (Sandbox Code Playgroud)

validation angular angular-reactive-forms

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

将FormGroup传递给多个组件

我在一个有角度的2+应用程序中使用反应式表单,并且需要将主FormGroup传递给多个组件,以便表单的不同部分(例如页眉,页脚等)可以在单独的组件中进行管理,并由这些不同的组件填充.这就是我现在这样做的方式:

<div class="container-fluid">
  <form [formGroup]="orderForm">
    <order-header [orderForm]="orderForm"></order-header>
    <order-items [orderForm]="orderForm"></order-items>
    <order-footer [orderForm]="orderForm"></order-footer>
  </form>
</div>
Run Code Online (Sandbox Code Playgroud)

我想知道,如果这是一个正确的方法因为我看到这个代码的警告/错误:

错误:ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后发生了变化.上一个值:'true'.当前值:'false'.

在这一行:

<form [formGroup]="orderForm">

有什么建议?谢谢.

typescript angular2-forms angular angular-reactive-forms

8
推荐指数
1
解决办法
6116
查看次数

使原始的角形控件变脏

Angular 4中有一个反应形式,某些控制应该在某个时刻以编程方式设置.

this.form = formBuilder.group({
  foo: ''
});
...
this.form.controls.foo.setValue('foo');
Run Code Online (Sandbox Code Playgroud)

如何控制原始/脏状态?目前我正在使用两者formfoo原始状态,例如:

<form [formGroup]="form">
  <input [formControl]="form.controls.foo">
</form>

<p *ngIf="form.controls.foo.pristine">
  {{ form.controls.foo.errors | json }}
</p>

<button [disabled]="form.pristine">Submit</button>
Run Code Online (Sandbox Code Playgroud)

如果pristine/dirty应该只指定人工交互并且不能以编程方式进行更改,那么这里有什么解决方案?

javascript typescript angular angular-reactive-forms

8
推荐指数
1
解决办法
2万
查看次数

子组件中的formControlName

我想创建一个自定义输入组件并在表单中重用它,但是我遇到了formGroup和formControlName的问题。

// Form
<form [formGroup]='loginForm'>
  <custom-input [myFormControlName]='email'></custom-input>
</form>

// CustomInput Component's Template
<input formControlName='myFormControlName'>
Run Code Online (Sandbox Code Playgroud)

问题似乎是formControlName预期与FormGroup指令一起使用,并且由于我在子组件中使用formControlName,所以找不到formControlName。有人知道如何解决该问题吗?

angular angular-reactive-forms

8
推荐指数
3
解决办法
5069
查看次数

Angular 4数组验证

我需要帮助以反应形式进行formArray验证.我想验证数组中的每个项目,但我不知道我该怎么做.谢谢.

HTML代码:

    <label for="name">name:</label>
    <input formControlName="name" id="name" type="text">
    <div *ngIf="name.invalid && (name.dirty || name.touched)">
       <div *ngIf="name.errors.required">
         required
       </div>
    </div>
Run Code Online (Sandbox Code Playgroud)

TypeScript代码:

 createForm() {
    this.form = this.fb.group({
      person: this.fb.array([this.initItemRows()])
    });
  }

initItemRows() {
    return this.fb.group({
      name: [''],
      info: ['']
    });
  }

  addNewRow() {
    const control = <FormArray>this.form.controls['person'];
    control.push(this.initItemRows());
  }

  deleteRow(index: number) {
    const control = <FormArray>this.form.controls['person'];
    control.removeAt(index);
  }

  get name() { return this.form.get('person.name'); }
  get info() { return this.form.get('person.info'); }
Run Code Online (Sandbox Code Playgroud)

我试过这个:

initItemRows() {
    return this.fb.group({
      name: ['', Validators.required …
Run Code Online (Sandbox Code Playgroud)

forms arrays validation angular angular-reactive-forms

8
推荐指数
1
解决办法
1万
查看次数

Angular 4获取Select控件的Selected选项文本

我想在Angular 4中获取Select控件的选择文本选项.

HTML:

<div class="col-sm-6 form-group">
<label>Industry</label>
<select   class="form-control select"  formControlName="Industry">
<option value="">Please select Value</option>  
<option *ngFor="let industry of industries"  
[ngValue]="industry.ID">{{industry.Name}}  
</option>  
</select> 
</div>


upload.component.ts
this.form.controls['Industry'].valueChanges.subscribe((name) => {
                this.form.controls['IndustryName'].setValue(name);
  });
Run Code Online (Sandbox Code Playgroud)

我正在使用Reactive的formControlName属性.

请建议回顾选定文本选择控件

angular angular-reactive-forms

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

如何重置Angular Reactive Form

我尝试过但未能找到重置角形的方法.

有人可以帮忙吗?

<form #thisIsAForm>
  <mat-form-field class="full-width">
    <input matInput placeholder="Weather">
  </mat-form-field>
</form>
<button mat-raised-button (click)="resetForm()">Reset</button>

export class Example{
  @ViewChild('thisIsAForm') thisIsAForm;

  resetForm() {
    this.thisIsAForm.reset();
  }
}
Run Code Online (Sandbox Code Playgroud)

angular angular-reactive-forms

8
推荐指数
1
解决办法
1万
查看次数

Reactive Angular表单等待提交时异步验证器完成

我正在构建一个反应式角形式,我正试图找到一种方法来触发提交时的所有验证器.如果验证者是同步的,那就没关系,因为我可以获得内联的状态.否则,如果验证器是异步验证器并且尚未触发验证器,则表单上的ngSubmit方法将处于挂起状态.我试图注册一个表单statusChange属性的订阅,但是当我通过markAsTouched函数调用manualy进行验证时它没有被触发.

这是一些片段:

   //initialization of form and watching for statusChanges
   ngOnInit() {
        this.ctrlForm = new FormGroup({
            'nome': new FormControl('', Validators.required),
            'razao_social': new FormControl('', [], CustomValidators.uniqueName),
            'cnpj': new FormControl('', CustomValidators.cnpj),
        });

        this.ctrlForm.statusChanges.subscribe(
            x => console.log('Observer got a next value: ' + x),
            err => console.error('Observer got an error: ' + err),
            () => console.log('Observer got a complete notification')
        )
    }
    //called on ngSubmit
    register(ctrlForm: NgForm) {
            Forms.validateAllFormFields(this.ctrlForm);
            console.log(ctrlForm.pending); 
            //above will be true if the async validator …
Run Code Online (Sandbox Code Playgroud)

javascript angular-validation angular angular-reactive-forms

8
推荐指数
3
解决办法
6331
查看次数

将Angular反应式FormControl传递给子组件

我有一个父组件,我想在其中创建和存储我的反应式表单。表单数组中将有多个表单组实例。我想将表单控件从每个表单组传递给子组件,但是在弄清楚如何做到这一点时遇到了麻烦。

这是一个Stackblitz,演示了我想做的事。另外,某些字段仅适用于汽车的某些“品牌”,这就是为什么我的html中包含以下行:

<input type="text" *ngIf="car.make != 'ford'" formControlName="model">
Run Code Online (Sandbox Code Playgroud)

我想将“详细信息”表单组字段移到“详细信息字段”子组件中,但是当我尝试这样做时,它告诉我我没有表单组实例,所以我知道父表单组是未在子组件中注册。任何帮助深表感谢。

components angular-components angular angular-reactive-forms angular-forms

8
推荐指数
1
解决办法
6834
查看次数

选择输入字段的浏览器建议时,Angular Pipe无法正常工作

我在输入字段上使用内置管道标题 - 在被动形式的用户名.只有当我在输入字段中输入时它才能正常工作,当我从该输入字段的浏览器建议中选择它时它就无法正常工作,即使我集中注意力也是如此.

app.component.ts

ngOnInit() {
    this.signupForm = new FormGroup({
      'userData': new FormGroup({
        'username': new FormControl(null, [Validators.required, this.forbiddenNames.bind(this)]),
        'email': new FormControl('abc@test.com', [Validators.required, Validators.email], this.forbiddenEmails)
      }),
      'gender': new FormControl('male'),
      'hobbies': new FormArray([])
    });
}
Run Code Online (Sandbox Code Playgroud)

app.component.html

<form [formGroup]="signupForm" (ngSubmit)="onSubmit()">
    <div formGroupName="userData">
        <div class="form-group">
           <label for="username">Username</label>
             <input
                  type="text"
                  id="username"
                  formControlName="username"
                  class="form-control"
                  [value]="signupForm.get('userData.username').value | titlecase">
                  <span *ngIf="signupForm.get('userData.username').errors['required']">
                      This field is required
                  </span>
          </div>
         ...
     </div>
     <button class="btn btn-primary" type="submit">Submit</button>
 </form>
Run Code Online (Sandbox Code Playgroud)

当我打字时它工作正常

在此输入图像描述

当我从浏览器选择中选择时它不起作用
虽然我从输入字段中聚焦它仍然是大写的.

在此输入图像描述 有人可以帮助我做错了什么.


@Haifeng Zhang这是我在问题中提到的场景,我在你的stackblitz演示中复制了

在此输入图像描述

angular-pipe angular angular-reactive-forms

8
推荐指数
1
解决办法
291
查看次数