标签: angular-reactive-forms

Angular - 反应式表单 - 如何使用类和验证器将对象传递到 FormGroup

我要创建一个大型表单,并决定使用反应式表单功能以方便使用。然而,我面临着一些可能显而易见的挑战并寻求帮助。

下面是两种情况,除了验证之外,它们产生相同的结果。该createFormWithValidation()方法指定了每个控件及其关联的验证器。该方法仅使用对象但不添加验证器createFromPassingObject()来创建相同的表单。this.party

我的目标是将一个对象传递给this.fb.group()该对象,该对象将具有属于该类的控件,并且能够为该类的每个属性指定验证器Party。

// The Class with the properties
export class Party {
  firstName: string = '';
  lastName: string = '';

  constructor() {}
}

// party Object
myForm: FormGroup;
this.party = new Party();

// Form with explicit controls and their validators

createFormWithValidation() {
  this.myForm = this.fb.group({
    firstName: [this.party.firstName, [Validators.required, Validators.minLength(3)]],
    lastName: [this.party.lastName, [Validators.required, Validators.minLength(3)]]
  })
}

// The goal is to achieve this type of method where this.party will be the …
Run Code Online (Sandbox Code Playgroud)

angular2-formbuilder angular angular-reactive-forms

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

使用反应形式以角度验证密码和确认密码

我在下面附上了我的代码。我在添加密码不匹配验证时遇到问题。如果我输入不匹配的密码,我不会收到验证错误

注册.component.html

<div class="form-group row mt-3">
 <label class="col-md-4 col-lg-4 text-center">UserName:<span style="color:red">*</span></label>
<input kendoTextBox required type="text" class="  col-md-6 col-lg-6 form-control " placeholder="Enter Your UserName " formControlName="username"/>
  <div *ngIf="(submitted||f2.username.touched) && f2.username.invalid" class="error-msg">
 <div *ngIf="f2.username.errors.required">UserName  is required</div>
 </div> </div>
 <div class="form-group row">
<label class="col-md-4 col-lg-4 text-center">Password:<span style="color:red">*</span></label>
<input kendoTextBox type="password" required  class="  col-md-6 col-lg-6 form-control " placeholder="Enter Your passowrd " formControlName="password"/>

 <div *ngIf="(submitted||f2.password.touched) && f2.password.invalid" class="error-msg">
<div *ngIf="f2.password.errors.required">password  is required</div>
<div *ngIf="f2.password.errors.minlength">minimum of 6 characters required</div>
    </div>
</div>
<div class="form-group row">
   <label class="col-md-4 …
Run Code Online (Sandbox Code Playgroud)

javascript validation angular angular-reactive-forms

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

FormControl 显示值

如何在输入 FormControl 中显示一些不等于此 FormControl 值的文本?

例如,从服务器获取一些对象 - {id: 1, name: "Name1"},并将valueFormControl 设置为该对象或 object.id 但display value设置为 object.name - "Name1"。

为什么我需要它:

我使用角材料自动完成并将 FormControl 的值设置为对象(来自选定的垫子选项)并通过 displayWith 将值显示为字符串。为了一些一致性和便利性,我想在从服务器获取数据时重复这种行为

angular angular-reactive-forms angular-forms

5
推荐指数
1
解决办法
4265
查看次数

以反应形式验证电子邮件和电话号码时面临的问题

我正在开发 Angular 应用程序,但在验证电子邮件和电话号码时遇到问题

问题

  1. 对于电子邮件验证问题,当我在错误的电子邮件中输入 @ 并且没有输入 .com 或 .in 示例时 -:abcd@gm .. 它不显示错误消息,

  2. 对于电话号码验证,仅当电话号码留空时才会显示错误消息,当我们输入电话号码并且超过最大长度或最小长度时,它不会显示任何错误消息。

组件.ts

import { Component, OnInit } from '@angular/core';
import { ServicesService } from '../service/services.service';
import { FormGroup  , FormControl  , Validators } from '@angular/forms';
@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.scss']
})
export class RegisterComponent implements OnInit {

 constructor( public restapi:ServicesService) {

    this.user = new FormGroup({

      email: new FormControl('', [Validators.required,Validators.email]),
      phone: new FormControl('', [Validators.required, Validators.minLength(10)]),
      password: new FormControl('', [Validators.required, Validators.minLength(6)])
      });

   }
ngOnInit() …
Run Code Online (Sandbox Code Playgroud)

angular angular-reactive-forms angular-forms

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

ngModel 在与 formControlName 相同的表单字段上

我曾经有一个没有任何验证的简单表单,其中的 HTML 大致如下所示:

<mat-form-field>
        <input matInput
               type="text"
               placeholder="TaskName"
               [(ngModel)]="todoListService.toDoData.taskName"
               formControlName="taskName"
               required
               required>
               [(ngModel)]="todoListService.toDoData.taskName"
        >
    </mat-form-field>
Run Code Online (Sandbox Code Playgroud)

然后我将我的表单移动到响应式表单并收到警告,我不能在与 formControlname 相同的字段上使用 ngModel。正在努力如何将表单中的数据分配到服务的输入字段。

HTMl 的当前部分:

<form [formGroup]="todoForm">
    <mat-form-field>
        <input matInput
               placeholder="TaskName"
               formControlName="taskName"
               required
               [(ngModel)]="todoListService.toDoData.taskName"
        >
    </mat-form-field>
Run Code Online (Sandbox Code Playgroud)

所以我删除了 ngModel 行并将其添加到我的 TS 中:

saveToDo() {
        this.dialogRef.close();
        this.todoListService.toDoData.taskName = this.todoForm.get('taskName');
        this.todoListService.toDoData.dueDate = this.todoForm.get('dueDate');
        this.todoListService.toDoData.extraNote = this.todoForm.get('extraNote');
        this.todoListService.addToDo();
    }
Run Code Online (Sandbox Code Playgroud)

我从中得到的错误是:

ERROR in src/app/new-to-do-dialog/new-to-do-dialog.component.ts(31,9): error TS2322: Type 'AbstractControl' is not assignable to type 'string'.
src/app/new-to-do-dialog/new-to-do-dialog.component.ts(32,9): error TS2322: Type 'AbstractControl' is not assignable to type 'DateConstructor'.
  Property 'prototype' is missing …
Run Code Online (Sandbox Code Playgroud)

angular angular-reactive-forms

5
推荐指数
1
解决办法
6789
查看次数

Angular 7:Formvalidation,Validators.pattern 不起作用

我只需要一个来自匹配整数的验证。因此我使用pattern带有正则表达式的验证器(见下文)。此外,该字段不应为空,因此我添加了required验证器。

但pattern错误永远不会被触发。我阅读了 angular 文档并查看了 的源代码,pattern但对我来说仍然没有意义。此外,我已经阅读了几乎所有与此主题相关的关于 stackoverflow 的问题。但我仍然无法弄清楚为什么该模式不起作用。

或许有大佬可以帮帮我,谢谢!

这是我的代码 component.ts:

// definition of the formcontrol
hours = new FormControl('', [
  Validators.required,
  Validators.pattern('^[0-9]*$'),
])

// for debugging
log() {
  console.log('required: ', this.hours.hasError('required'));
  console.log('pattern: ', this.hours.hasError('pattern'));
  console.log('Erros: ', this.hours.errors);
}
Run Code Online (Sandbox Code Playgroud)

模板:

<mat-form-field>
  <input matInput [formControl]="hours" (input)="log()"
    placeholder="Anzahl der ausbezahlten Überstunden" type="number">
  <mat-error *ngIf="hours.hasError('required') && !hours.hasError('pattern')">
    Anzahl der Überstunden fehlt!
  </mat-error>
  <mat-error *ngIf="!hours.hasError('required') && hours.hasError('pattern')">
    Anzahl muss eine Ganzzahl sein!
  </mat-error>
</mat-form-field>
Run Code Online (Sandbox Code Playgroud)

例子inputValue="": …

typescript angular angular-reactive-forms angular7

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

将 formControlName 传递给 Angular 组件

我有一个反应形式。设置与此类似:

myForm: FormGroup;

    this.myForm= new FormGroup({
        name: new FormControl("", [Validators.required, Validators.maxLength(15), Validators.pattern('...')]),
        ...
    });
Run Code Online (Sandbox Code Playgroud)

我在我的表单上使用它,如下所示:

  <input
    type="text"
    formControlName="name"
  />
  <div *ngIf="name.errors?.required">
      Name is required
  </div>
  <div *ngIf="name.errors?.maxlength">
      Name must be {{ name.errors.maxlength.requiredLength }} characters        
  </div>
  <div *ngIf="name.errors?.pattern">
      Name has invalid characters.
  </div>
Run Code Online (Sandbox Code Playgroud)

这只是我表格的精简版。我有多个输入,我不得不为每个输入创建错误 div。

所以为了解决这个问题,我尝试创建一个组件。该组件与上面的代码非常相似:

  <input
    type="text"
    [formControlName]="formControlName"
  />
  <div *ngIf="name.errors?.required">
      Name is required
  </div>
  etc...
Run Code Online (Sandbox Code Playgroud)

.ts 文件:

@Component({
  selector: 'app-text',
  templateUrl: './text.component.html'
})
export class TextComponent  {

  @Input() formControlName: FormControl;
}
Run Code Online (Sandbox Code Playgroud)

所以在我的表单上,我想使用这个组件如下:

<app-text [formControlName]="name"></app-text>
Run Code Online (Sandbox Code Playgroud)

但是我不能让它与 formControlName 属性一起使用。

这可能吗?

谢谢 …

angular-components angular angular-reactive-forms controlvalueaccessor

5
推荐指数
1
解决办法
3110
查看次数

为什么 Angular ReactiveForms FormArray 会抛出错误“TypeError:无法读取 null 的属性‘updateOn’”

大家好,我有一个具有一组角色的 Formarray。在编辑期间,它会动态删除并在该表单数组中添加角色,直到这里一切正常,但是当我提交表单时,它会引发错误并且页面会刷新。

错误:TypeError:无法读取 null 的属性“updateOn”

我还附上了下面的屏幕截图在此处输入图片说明

form-control angular-reactive-forms formarray angular6

5
推荐指数
1
解决办法
1717
查看次数

ngIf 角反应形式分量值

我有一组单选按钮。如果用户选择值“是”,我想在表单上显示一个附加框。

https://stackblitz.com/edit/angular-4bgahw?file=src/app/personal/personal.component.ts

HTML.component

<div formGroupName="radioButtonsGroup" class="form-group col-6 pl-0 pt-3">

    <div class="form-check-inline" *ngFor="let item of personal.radioButtonsdata">
        <label for="{{item.section}}" class="col-12 customradio"
            ><span>{{item.section}}</span>
            <input [value]="item" id="{{item.section}}" type="radio" formControlName="selectedButton"/>
            <span class="checkmark"></span>
        </label>
    </div>

    <!-- <div class="col-md-8" *ngIf="selectedButton.control.item === 'yes'"> --> //my attempt to target above input value
  <div class="col-md-8" >
        <input type="text" formControlName="title" class="form-control" placeholder="Title">
</div>
    </div>
Run Code Online (Sandbox Code Playgroud)

任何人都可以让它工作并告诉我我在这里做错了什么吗?

javascript typescript angular angular-reactive-forms

5
推荐指数
2
解决办法
4893
查看次数

Angular 在父组件嵌套表单中使用子组件表单

将子组件表单放入父组件表单的最佳方法是什么?我们使用的是 2019 年最新的 Angular 8。经过研究,以下方法不能完全奏效。

父组件:

 ngOnInit() {
    this.parentForm = this.fb.group({
       childForm1: etc
    })
Run Code Online (Sandbox Code Playgroud)

子组件:

this.ChildForm = this.formBuilder.group({
  'streetNumber': [null, [Validators.required, Validators.maxLength(32)]],
  'streetType': [null, [Validators.maxLength(8)]],
  'city': [null, [Validators.maxLength(32)]],
  'state': [null, [Validators.maxLength(16)]],
  'postalCode': [null, [Validators.maxLength(16)]],
}, { validator: atLeastOneLocationRequired })
Run Code Online (Sandbox Code Playgroud)

}

方法一:

这个方法,https: //itnext.io/partial-reactive-form-with-angular-components-443ca06d8419 经过严格测试表明 ParentForm 有效,即使 Child Form 无效。这不应该发生。

ngOnInit() {
  this.parent = this.fb.group({
    fullName: null
  })
Run Code Online (Sandbox Code Playgroud)

}

formInitialized(name: string, form: FormGroup) {
  this.checkoutForm.setControl(name, form);
}
Run Code Online (Sandbox Code Playgroud)

方法二:

方法 2 使用 ViewChild,这是听力不好的做法。 https://davembush.github.io/attaching-an-angular-child-component-s-form-to-a-parent/

@ViewChild(ChildComponent) childComponent: ChildComponent;

And now in ngAfterViewInit() …
Run Code Online (Sandbox Code Playgroud)

typescript angular angular-reactive-forms angular8

5
推荐指数
1
解决办法
7925
查看次数