标签: angular-forms

Angular 2:在某些条件下应用Validator.required验证

我有一个有角度的2形式,其中我必须在某些条件下需要一个字段,如:

description:  ['', Validators.required]
Run Code Online (Sandbox Code Playgroud)

仅在某些类型的条件下才需要此描述字段,例如:

if(true){descReq = true};
Run Code Online (Sandbox Code Playgroud)

我怎么能做到这一点,请建议.提前致谢!

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

6
推荐指数
2
解决办法
2059
查看次数

多个自定义验证器,其反应形式为角度2

我有两个自定义validatorreactive form,我叫下面的函数来创建组件构造函数形式:

private createForm(): void {
this.passwordUpdateForm = this.formBuilder.group({
    newpassword : [null, Validators.required],
    passwordconfirm: [null, Validators.required]
},
{
    validator: [PasswordValidation.PasswordMatch, PasswordValidation.PasswordRule] // validation method

});
Run Code Online (Sandbox Code Playgroud)

}

PasswordValidation是一个具有以下两个功能的类

    export class PasswordValidation {

     public  static PasswordMatch(control: AbstractControl) {
        let password = control.get('newpassword'); // to get value in input tag
        if(password){
            let confirmPassword = control.get('passwordconfirm').value; // to get value in input tag
            if (password.value !== confirmPassword) {
                control.get('passwordconfirm').setErrors({ ['passwordmatch'] : true});
            }else {
                return null;
            }
        }
    } …
Run Code Online (Sandbox Code Playgroud)

custom-validators angular-validation angular angular-reactive-forms angular-forms

6
推荐指数
1
解决办法
6199
查看次数

Angular FormArray:引用模板中动态添加的FormControl

我正在使用Angular Reactive表单,已向FormArray中动态添加了两个FormControl,但是在将它们与formControlName绑定时,却无法在模板中引用这些FormControl。在模板中,我将循环索引变量“ i”分配给formControlName,但它不起作用。通过将控件与formControlName绑定,可以得到“具有路径的窗体控件没有值访问器”。这是我的组件类代码:

export class Control {
  constructor(public controlType?: string, public label?: string, public required?: boolean, public placeholder?: string,
    public options?: string[], public value?: string) { }
}

export class FormComponent implements OnInit {
  reviewForm: FormGroup;

  constructor(public formService: FormService, public dialog: MdDialog) { }


  selectedControl: any = null;
  label: string;

  ngOnInit() {
    this.reviewForm = new FormGroup({
      'controlArray': new FormArray([
      ])
    });
  }

  addControl() {
    const myControl: Control = new Control(this.selectedControl.name, this.label, this.isRequired,
      this.selectedControl.attributes.value, this.selectedControl.attributes.options, 'null');
    var control: FormControl = new …
Run Code Online (Sandbox Code Playgroud)

form-control angular angular-reactive-forms angular-forms formarray

6
推荐指数
1
解决办法
5330
查看次数

* ngFor中的mat-datepicker

使用mat-datepickerinside 时会遇到此问题*ngFor

mat-datepicker需要模板引用变量#test才能绑定到input。通常,在
使用inside时*ngFor,是否有直接的方法来获取参考变量?我找不到办法。

没有的简单工作示例 *ngFor

<mat-form-field>
  <input matInput [matDatepicker]="test" placeholder="Enter Date" [(ngModel)]="someDate" name="someDate">
  <mat-datepicker-toggle matSuffix [for]="test"></mat-datepicker-toggle>
  <mat-datepicker #test></mat-datepicker>
</mat-form-field>
Run Code Online (Sandbox Code Playgroud)

但是由于模板reference variables对于整个模板必须是唯一的,因此mat-datepicker当在内重复上述块时,就不能直接使用for场景*ngFortest因为它不是唯一的。

任何指针都会有所帮助。

datepicker angular-material angular angular-forms

6
推荐指数
2
解决办法
3070
查看次数

使用FormBuilder创建禁用的表单组

假设我们有myFormGroup通过FormBuilder初始化的:

this.myFormGroup = this.fb.group(
  {
    field1: ['', SomeValidator1],
    field2: ['', AnotherValidator2],
    field3: [''],
    ...
  }
);
Run Code Online (Sandbox Code Playgroud)

我知道我们可以禁用特定的表单控件,例如:

fb.control({value: 'my val', disabled: true});
Run Code Online (Sandbox Code Playgroud)

当然,我可以在示例中使用此语法,并将组中的每个控件标记为已禁用。但是表单组可能有很多控件。

因此,问题-是否有任何方法可以通过FormBuilder 创建(而不是之后)禁用整个FormGroup / FormArray的同时

ps我问这个问题的原因是因为我需要有条件地初始化具有不同类型用户权限的活动或禁用字段的表单组。

angular angular-reactive-forms angular-forms

6
推荐指数
2
解决办法
2303
查看次数

带可编辑字段的角度材料表

我正在使用角度材料从数组形式的数据创建表格。这一切都很好。我遇到的问题是字段本身需要是表单字段。它们需要从数据中填充,但可编辑。此外,带有空白字段的新行应该是可填充和持久化的。我发现虽然行数据填充,但值永远不会进入表单字段本身,或者表单字段都只由第一条记录填充。我引用字段值的方式有问题,但我看不到它是什么。所以,这是 html 中的表格:

<form #a="ngForm" >
  <mat-table #approvalsTable [dataSource]="approvalsDataSource"
             #approvalsSort="matSort" matSort matSortActive="description"
             matSortDirection="asc" style="width:900px;font-family: Arial, Helvetica, sans-serif; font-size:14px;">

    <ng-container matColumnDef="description">
      <mat-header-cell *matHeaderCellDef mat-sort-header>Description</mat-header-cell>
      <mat-cell *matCellDef="let element; let i = index">
        <input type="text"
               name="description" [(ngModel)]="element.description" [value]="element.description">
        {{element.description}}

      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="approvalNumber">
      <mat-header-cell *matHeaderCellDef mat-sort-header>Approval No.</mat-header-cell>
      <mat-cell *matCellDef="let element; let i = index">
        <input type="text"
               name="approvalNumber" [(ngModel)]="element.approvalNumber" [value]="element.approvalNumber">
        {{element.approvalNumber}}

      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="expires">
      <mat-header-cell *matHeaderCellDef mat-sort-header>Expiration Date</mat-header-cell>
      <mat-cell *matCellDef="let element; let i = index">
        <input type="text"
               name="expires" [(ngModel)]="element.expires" [value]="element.expires">
        {{element.expires}}

      </mat-cell>
    </ng-container> …
Run Code Online (Sandbox Code Playgroud)

angular-material2 angular-forms angular5

5
推荐指数
0
解决办法
6516
查看次数

FormArray 控件的 valueChanges 未触发

我正在尝试以 angular 5 反应形式捕获 FormArray 控件的 valueChanges 事件。我有正常的表单组 valueChanges 事件和相同的工作正常但不适用于 formArray 控件。

我已将我的表单组定义为 -

this.ApplicationForm = this.fb.group({
  ApplicationPenalties: this.fb.array([this.preparePenaltyDetails()])
});
Run Code Online (Sandbox Code Playgroud)

并初始化表单数组如下 -

preparePenaltyDetails(): FormGroup {
    return this.fb.group({
      Id: '',
      ApplicationId: '',
      RevisionNo: '',
      PenaltyMwh: ''
    });
  }
Run Code Online (Sandbox Code Playgroud)

当我从我的 api 获取数据时,我将控件设置为 -

this.ApplicationForm.setControl('ApplicationPenalties', this.fb.array(this.application.ApplicationPenalties
              .map(x => this.fb.group(x)) || []));
Run Code Online (Sandbox Code Playgroud)

我的 html 模板如下 -

<div formArrayName="ApplicationPenalties" *ngFor="let penalty of ApplicationPenalties.controls; let i=index">
                    <div [formGroupName]="i">
                      <div class="row pocCharges">
                        <div class="col-md-6">
                          <div class="form-group">
                            <h4 class="d-sm-block">Revision Number</h4>
                            <div class="input-group">
                              <input class="form-control form-control-sm" formControlName="RevisionNo" type="text">
                              <span …
Run Code Online (Sandbox Code Playgroud)

angular angular-reactive-forms angular-forms formarray angular5

5
推荐指数
0
解决办法
9188
查看次数

如何在 FormArray 中添加 Angular Material 自动完成

我正在使用 Angular 6。我的表单有一个formArray我在单击按钮时添加项目的表单。我的表格看起来像

private initForm() {
  this.orderForm = new FormGroup({
    'orderItems': this.orderItems,
    'customerContact': new FormControl(null),
    'totalAmount': new FormControl(null)
  });
}

onAddItem() {
  (<FormArray>this.orderForm.get('orderItems')).push(
    new FormGroup({
      'itemName': new FormControl(null, Validators.required),
      'itemService': new FormControl(null, Validators.required),
      'itemPrice': new FormControl(null)
    })
  );
}
Run Code Online (Sandbox Code Playgroud)

html代码

<tbody formArrayName="orderItems">
  <tr *ngFor="let orderItem of getControls(); let i = index" [formGroupName]="i">
    <td>
      <input type="text" formControlName="itemName" class="form-control" [matAutocomplete]="autoName">
      <mat-autocomplete #autoName="matAutocomplete">
        <mat-option *ngFor="let option of filteredOrderItems | async" [value]="option">
          {{option}}
        </mat-option>
      </mat-autocomplete>
    </td>
    <td>
      <input type="text" formControlName="itemService" class="form-control" [matAutocomplete]="autoService"> …
Run Code Online (Sandbox Code Playgroud)

angular-material angular angular-forms

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

ChangeDetectionStrategy.OnPush 打破 ControlValueAccessor 的禁用状态

在我的 Angular 应用程序中,我通过实现ControlValueAccessor接口创建了一个自定义表单元素。

因此,在我的组件中,我正确实现了该接口的所有方法,包括setDisabledState

/**
 * This function is called when the control status changes to or from "disabled".
 * Depending on the value, it will enable or disable the appropriate DOM element.
 *
 * @param isDisabled
 */
setDisabledState(isDisabled: boolean): void {
  this.disabled = isDisabled;
}
Run Code Online (Sandbox Code Playgroud)

一切正常。

问题是当我将组件的ChangeDetectionStrategy更改为OnPush.

通过这样做,我的组件的启用/禁用功能被破坏了。

typescript angular-components angular angular-forms

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

将自定义组件添加到响应式表单的 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
查看次数