首页 > 解决方案 > 获取formGroup中的表单id

问题描述

我正式使用 ngx 来构建表单。我需要的是在我拥有的一些自定义类型中访问表单 ID。基本上我需要访问formGroup 中的表单ID。

HTML

   <div>
        <form [formGroup]="form" [id]="formId">
            <formly-form [form]="form" [model]="model" [fields]="fields" [options]="options"></formly-form>
        </form>
    </div>

.ts

 formId = "unique_id_from_backend"
 form = new FormGroup({});

输入类型组件

@Component({
    selector: 'input-field',
    templateUrl: './input.html',
})
export class InputFieldComponent extends FieldType implements OnInit {

    ngOnInit(): void {
        console.log(this.form);
        // here i can access formGroup that i am passing in <form> but it seems id property is 
        // not there. Is there some way i can access form id?
    }

}

标签: angulartypescriptformsangular-reactive-formsngx-formly

解决方案


在自定义字段类型中,您可以访问字段和选项实例,您可以在其中获取 id、key...

对于您的用例,您可以依赖formState,因此将其分配formIdoptions.formState

  form = new FormGroup({});
  options = { formState: { id: "unique_id_from_backend" } }
export class InputFieldComponent extends FieldType implements OnInit {
  ngOnInit(): void {
    console.log(this.formState.id);
  }
}

推荐阅读