标签: angular-reactive-forms

组 angular 6 中的嵌套 formarray

再会。

我寻找了解决方案,即使有一个与我所问的类似的问题,我相信这个问题更独特一些,而不是重复。

这是我的 html 表单:

<div class="form-group col-md-6" formGroupName="schema">
  <div formArrayName="currencies">
    <input type="text" class="form-control" id="percentage" formControlName="percentage" placeholder="Discount %*" required>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

这是我的 ts formBuilder。

this.createPromo = this.fb.group({
      type: ['promotion'],
      name: ['', Validators.required],
      description: ['', Validators.required],
      enabled: ['', Validators.required],
      promotion_type: ['', Validators.required],
      start: ['', Validators.required],
      end: ['', Validators.required],
      schema: this.fb.group({
        currencies: this.fb.array([
          this.fb.group({
            percentage: '',
            currency: 'ZAR'
          })
        ])
      }),
    });
Run Code Online (Sandbox Code Playgroud)

所以我希望我的表单作为分组数组提交。然而,控制台中的错误如下Cannot find control with path: 'schema -> currencies -> percentage',因此percentage即使我输入了一个数字,我也无法将我的表单提交为空。

angular angular-reactive-forms formarray

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

将自定义组件添加到响应式表单的 FormGroup 的正确方法是什么?

我在包装 mat-select 的自定义组件上使用 formControlName 时遇到很多问题。

现在看来我的自定义控件找不到表单组?即使自定义元素嵌套在 formGroup 下。

我有一个StackBlitz

但是当我将自定义组件嵌套在 formGroup 下时,问题就出现了,所有其他控件都可以找到 formGroup 但我的自定义组件似乎无法找到。

<form novalidate [formGroup]="tenantForm">
    <label for="Id">Id</label>: <input class="form-control" formControlName="id" id="Id" name="Id" />
    <custom-component-with-mat-select formControlName="culture" id="Culture" name="Culture"></custom-component-with-mat-select>
</form>
Run Code Online (Sandbox Code Playgroud)

在这个例子中,Id 字段可以正常工作,但是 Culture 字段抱怨没有嵌套在 FormGroup 中?

错误:formControlName 必须与父 formGroup 指令一起使用。您需要添加一个 formGroup 指令并将其传递给现有的 FormGroup 实例(您可以在类中创建一个)。

自定义组件应该如何与响应式表单和表单组一起使用?

我最初的问题是不记得导入 ReactiveFormsModule .. 也许我忘记再次导入某些东西?

这个答案是实现这一目标的设计方法吗?或者我错过了一个更简单的解决方案?

我需要实现一个控制值访问器吗??正如这里所解释的

只是对设计的方式感到困惑。

我的组件包装了 angular material 的 mat-select,如果我需要在 mat-select 上放置属性或让我的组件实现控制值访问器,我想我也很困惑?似乎没有任何效果。

angular-material angular angular-reactive-forms angular-forms

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

如何以编程方式验证反应式表单控件?

我有一个FormGroup我的反应形式的对象。现在我想以编程方式触发表单验证。

我已经用这段代码检查了表单,但是我的控件 css 状态类没有设置,就像当我单击控件并在控件外单击时那样。

if (!this.formGroup.valid) {
  // TODO: Fix that invalid controls don't get highlighted
  return;
}
Run Code Online (Sandbox Code Playgroud)

angular angular-reactive-forms

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

angular 5 基于另一个字段的值有条件地验证字段

如何根据另一个字段的值有条件地验证一个字段?这是我尝试过的,但似乎不起作用

this.PDform = _formbuilder.group({
    [...]
    'intlNumber': ['',this.nationality == 'Abroad' ? Validators.compose([Validators.pattern(this.phoneNumberExp), Validators.maxLength(14), Validators.minLength(11), Validators.required]) : Validators ]
    [...]
})
Run Code Online (Sandbox Code Playgroud)

angular-validation angular angular-reactive-forms angular-forms angular5

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

表格数组。找不到路径控制

我想输出一个表单,其中一个字段是一个数组,对于数组的每个元素,我需要输出我的输入。

成分:

ngOnInit() {
  const fb = this.fb;
  this.editForm = this.fb.group({
    country: fb.control(null),
    identifiers: this.fb.array([
       this.fb.group({
         codeIdentifier: fb.control(null),
         numIdentifier: fb.control(null),
       })
    ]),
 });
 this.organizationService.getOneById(this.id).subscribe((organization: Organization) => {
    let ids: any[] = [];
    organization.identifiers.forEach(item => {
       let id: any = { "codeIdentifier": "", "numIdentifier": "" };
       id.codeIdentifier = item.typeIdentifier.code;
       id.numIdentifier = item.numIdentifier;
       ids.push(id);
    });
     this.editForm.setControl('identifiers', this.fb.array(ids || []));
 })
}
Run Code Online (Sandbox Code Playgroud)

HTML:

<div [formGroup]="editForm">
  <ng-container formArrayName="identifiers">
    <ng-container *ngFor="let identifier of identifiers.controls; let i=index" [formGroupName]="i">
      <input type="text" formControlName="codeIdentifier">
      <input type="text" formControlName="numIdentifier">
    </ng-container>
  </ng-container> …
Run Code Online (Sandbox Code Playgroud)

angular angular-reactive-forms angular5

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

Angular Reactive Forms,formName.reset() 工作但抛出错误“control.value is null”并且所有字段都标记为“red”并且无效?

我有一个角度反应形式,提交时我有这个代码:

(ngSubmit)="addVideo(); addVidForm.reset();"
Run Code Online (Sandbox Code Playgroud)

我正在标记我的主要表格 #addVidForm

我还有一些自定义验证器/控件,它们与我拥有的另一种表单相比很特别,在重置表单时不会发生这种情况。

我的验证器如下:

 static mustBeVimeo(control: AbstractControl) : ValidationErrors | null {

        if((control.value as string).startsWith("https://vimeo.com/")){ return null } else
        if((control.value as string).startsWith("http://vimeo.com/")){ return null }
        else { return { mustBeVimeo : true } }

}
Run Code Online (Sandbox Code Playgroud)

这是我在后端的表单:

this.addVideoForm = new FormGroup({
      title: new FormControl('', [Validators.required, Validators.minLength(3), Validators.maxLength(50)]),
      description: new FormControl('', [Validators.required, Validators.minLength(5), Validators.maxLength(200)]),
      category: new FormControl('', [Validators.required]),
      link: new FormControl('', [Validators.required, AddVideoValidators.mustBeVimeo, Validators.maxLength(100)]),
      visibleToGuests: new FormControl(this.visibleToGuests, [Validators.required])
    })
Run Code Online (Sandbox Code Playgroud)

我还做了一个函数,它只是在后端重置表单并用一个按钮调用它,我得到了同样的错误。

不完全确定这整个事情的哪一部分失败了。该字段是正常输入,就像我在其他地方使用的一样。

angular angular-reactive-forms angular-forms angular7

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

将 FormControl 传递给子组件 - 没有未指定名称的表单控件的值访问器

我有一个输入组件customInput,它创建一个经典的输入字段并为其添加一些布局香料,没有额外的逻辑。

我想将一个 formControl 传递给它,将它绑定到它包含的输入。

应该这样使用:

<form [formGroup]="form">
  <custom-input [formControl]="form.controls['control']"></custom-input>
</form>
Run Code Online (Sandbox Code Playgroud)

内部自定义输入:

export class HidInputFieldComponent  {
   @Input() formControl: AbstractControl

   ...
}

<div class="container">
  <input [formControl]="formControl"/>
    <label>label</label>
</div>
Run Code Online (Sandbox Code Playgroud)

现在当我初始化组件时,我得到

未指定名称的表单控件没有值访问器

在我的组件构造函数中记录控件,它是未定义的。

我做错了还是没有办法解决ControlValueAccessor?由于我实际上并没有构建自定义控件(我仍然使用经典输入),因此看起来很极端

angular angular-reactive-forms angular-forms

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

带有(反应式)表单的 Angular CDK 拖放

我有这个例子:https : //stackblitz.com/edit/angular-asevei?file=app%2Fcdk-drag-drop-sorting-example.html

一切正常,但是在 将选择框“重置”到列表中的第一个值时。

有没有什么办法解决这一问题?它只是视觉上的,但对用户来说非常刺耳。我曾尝试使用该cdkDragPreview选项,但无法使其正常工作。

成分:

import { Component } from '@angular/core';
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';

@Component({
    selector: 'cdk-drag-drop-sorting-example',
    templateUrl: 'cdk-drag-drop-sorting-example.html',
    styleUrls: ['cdk-drag-drop-sorting-example.css'],
})
export class CdkDragDropSortingExample {

    myForm: FormGroup;

    constructor(private fb: FormBuilder) {
    this.myForm = this.fb.group({
        title: ['title'],
        items: fb.array([
        fb.group({
            name: fb.control('1'),
            note: fb.control('quux')
        }),
        fb.group({
            name: fb.control('2'),
            note: fb.control('bar')
        }),
        fb.group({
            name: fb.control('3'),
            note: fb.control('baz')
        })

        ])
    })
    }

    drop(event: …
Run Code Online (Sandbox Code Playgroud)

angular angular-reactive-forms angular-cdk

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

动态添加行:Angular Reactive-Form

我想在单击 时动态添加行button。我为此使用反应形式。 这就是我要说的

这是我的 html 代码

<table>
    <thead>
        <tr class='tableHeader'>
            <div fxLayout="row" fxLayoutAlign="start center" fxFlex="1 0 auto">
                <td fxFlex="22" class="pr-4">Name</td>
                <td fxFlex="15" class="pr-4">Price</td>
                <td fxFlex="15" class="pr-4">Loan Term</td>
                <td fxFlex="15" class="pr-4">Quantity</td>
                <td fxFlex="15" class="pr-4">Deposit</td>
                <td fxFlex="15" class="pr-4">Total</td>
            </div>
        </tr>
    </thead>
    <tbody>
        <tr [formGroup]="loanProductForm">
            <div fxLayout="row" fxLayoutAlign="start center" fxFlex="1 0 auto">
                <td fxFlex="22">
                    <mat-form-field appearance="outline" fxFlex="100" class="pr-4">
                        <mat-label>Product </mat-label>
                        <mat-select formControlName="productId" required>
                            <mat-option *ngFor="let product of productList" [value]="product.productId">
                                {{product.name}}
                            </mat-option>
                        </mat-select>
                    </mat-form-field>
                </td>
                <td fxFlex="15">
                    <mat-form-field appearance="outline" fxFlex="100" class="pr-4">
                        <mat-label>Price </mat-label> …
Run Code Online (Sandbox Code Playgroud)

javascript angular angular-reactive-forms

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

Angular:在异步调用和 AsyncPipe 后创建动态反应表单

我执行异步服务调用来获取元素列表。

 public elementList: Array<Element>;
   ... 
   this.service.getElementList().subscribe( list => {
       this.elementList = list;
       this.createFormGroup(list);
     }
   );
   ...
Run Code Online (Sandbox Code Playgroud)

当我收到元素列表(我订阅了服务调用)时,我根据元素列表构建表单组。在模板中,我有一个 *ngIf 仅当列表大于零时才绘制。

*ngIf="elementList?.length>0"
Run Code Online (Sandbox Code Playgroud)

由于elementList是异步获取的,所以这个ngIf不起作用。我读到可以将 ngIf 与 AsnycPipe 一起使用。所以在模板中我将有:

*ngIf="elementList$ && elementList$.length>0"
Run Code Online (Sandbox Code Playgroud)

其中 elementList$ 是从服务调用返回的 Observable。

   public elementList$: Observable<Array<Element>>;   

   elementList$ =this.service.getElementList()
Run Code Online (Sandbox Code Playgroud)

我想知道收到 elementList 后如何创建 FormGroup。首先,我需要创建 FormGroup,然后模板应该调用 *ngIf 来绘制元素。

angular angular-reactive-forms async-pipe

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