如何在角度反应形式输入中添加“必填字段”星号

新手上路,请多包涵

我正在开发一种具有反应性动态角度形式的应用程序。此表单字段来自 API 请求并动态生成。

我真的需要在我的表单输入中添加“必填字段”星号 (*),这是必需的。如何做到这一点?

下面是我的表单字段的样子。

 <ng-container *ngIf="input1.type=='string'" [hidden]="False">
 <div>
  <mat-form-field>
   <input matInput   [formControlName]="input1.field_name"  type="text"  placeholder="{{input1.title}}">
  </mat-form-field>
 </div>
</ng-container>

原文由 Talk is Cheap Show me Code 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 587
1 个回答

首先创建一个指令来添加星号而不弄乱输入属性:

 import { AfterContentChecked, Directive, Optional } from "@angular/core";
import { AbstractControl } from "@angular/forms";
import { MatFormField, MatInput, MatSelect } from "@angular/material";

/**
 * Input/Select into FormField consider Validator.required from reactive form if the [required] attribute is missing in the template
 */
@Directive({
  selector: 'mat-form-field:has(input:not([required])), mat-form-field:has(mat-select:not([required]))'
})
export class ReactiveAsteriskDirective implements AfterContentChecked {
  constructor(@Optional() private matFormField: MatFormField) { }

  ngAfterContentChecked() {
    if (this.matFormField) {
      const ctrl = this.matFormField._control;
      if (ctrl instanceof MatInput || ctrl instanceof MatSelect)
        if (ctrl.ngControl)
          if (ctrl.ngControl.control)
            if (ctrl.ngControl.control.validator)
              if (ctrl.ngControl.control.validator({} as AbstractControl))
                ctrl.required = ctrl.ngControl.control.validator({} as AbstractControl).required;
    }
  }
}

现在您可能想让星号显示为红色,因为它表示需要输入。为此,请将其添加到您的组件 CSS 中:

 :host ::ng-deep .mat-placeholder-required {
  color: red;
}

原文由 Diego Victor de Jesus 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题