如何设置可选或条件表单ControlName?

问题描述 投票:0回答:1

长话短说:

我正在寻找一种能够根据某些条件添加/填充或不添加属性“formControlName”的方法。 null/空字符串值对我来说没问题,但 Angular 不允许我这样做。

更多信息: 我创建了一些自定义表单组件,其中包含本机 HTML 表单元素。 我想在有或没有 ReactiveForms 的情况下使用这些组件,因此我需要能够指定或不指定 formControlName 属性。当我需要使用 ReactiveForms 时,我只需在父级中添加一个 FormGroup 来调用我的组件。它已经可以工作了,因为我使用了:

viewProviders: [{ provide: ControlContainer, useExisting: FormGroupDirective }].

我只需要解决条件表单ControlName属性的问题。

这是我已经尝试过的:

<input [formControlName]="(isSomething) ? 'my-name' : ''" />
<input [formControlName]="(isSomething) ? 'my-name' : null" />
<input [formControlName]="(isSomething) ? 'my-name' : false" />

不起作用:Angular 对我大喊大叫。

<input [attr.formControlName]="" />

不起作用:使用 formcontrolname="" 进行渲染(小写,并被 FormGroup 忽略)

为了达到同样的目标,是否可以根据条件添加或不添加属性?

<input
  id="stuff-1"
  class="stuff"
  (cond === true) [formControlName]="my-name" // only if condition is true
  (cond === false) // do nothing
/>

我也尝试过使用自定义指令,但不知道如何使其工作。 我发现的唯一选择是在容器上有一个

*ngIf
和两个单独的输入......

<ng-container *ngIf="false">
  <input
     id="stuff-1"
     class="stuff"
  />
</ng-container>

<ng-container *ngIf="true">
  <input
    id="stuff-1"
    class="stuff"
    [formControlName]="name"
  />
</ng-container>
angular angular-reactive-forms angular-forms
1个回答
0
投票

这可能有点矫枉过正,但你可以考虑这样的指令:

import { Directive, Input, ViewContainerRef } from '@angular/core';

@Directive({
  selector: '[appConditionalName]',
  standalone: true
})
export class ConditionalNameDirective {
  @Input() readonly appConditionalName: string = '';
  @Input('condition') readonly condition: boolean = false;

  constructor(
        private readonly viewContainerRef: ViewContainerRef
  ) { }

  ngAfterViewInit(): void {
        if (this.condition) {
      const el = this.viewContainerRef.element.nativeElement as HTMLInputElement;

      el.setAttribute('formControlName', this.appConditionalName);
        }
    }
}

请参阅此处的示例:https://stackblitz.com/edit/conditional-formcontrolname

© www.soinside.com 2019 - 2024. All rights reserved.