typescript 在表单内创建动态表单字段,并在Angular 中进行动态验证

pn9klfpd  于 2022-12-27  发布在  TypeScript
关注(0)|答案(2)|浏览(218)

我有这些数据

"data": [
            {
                "sno": 1,
                "name": "name",
                "nameLabel": "Name",
                "isRequired": 1,
                "maxLen": 50,
                "order": 1,

            },
            {
                "sno": 2,
                "name": "desc",
                "nameLabel": "Description",
                "isRequired": 1,
                "maxLen": 50,
                "order": 2,
            },
            ..
            ..

我必须在表单中动态创建这些字段,并使用动态验证。如果isRequired为1,则该字段是必需的,maxLen也必须进行验证。
有办法吗谢谢

zbq4xfa0

zbq4xfa01#

按以下方式操作:)

for (const field of this.data) {
      let validators = [];
      if (field.isRequired) {
        validators.push(Validators.required);
      }
      if (field.maxLen) {
        validators.push(Validators.maxLength(field.maxLen));
      }
      this.form.addControl(field.name, this.fb.control('', validators));
    }
omjgkv6w

omjgkv6w2#

您的HTML应该类似于

<form *ngIf="Data != null && Data.length > 0" [formGroup]="rForm">
  <div class="col-lg-4 col-md-12 col-12">
    <div class="form-group" *ngFor="let control of rForm.value | keyvalue">
        <label for="">Email</label>
        <input type="text" class="form-control" placeholder="Email" [formControlName]="control.key">
        <span *ngIf="form.get(control.key).errors?.required">Field is required</span>
    </div>
  </div>
</form>

你的 typescript 应该像

for (const field of this.data) {
  let validators = [];
  if (field.isRequired) {
    validators.push(Validators.required);
  }

  if (field.maxLen) {
    validators.push(Validators.maxLength(field.maxLen));
  }

  this.form.addControl(field.name, this.fb.control('', validators));
}

谢谢!

相关问题