angulartypescriptformsangular-reactive-formsngx-formly

Get form id in formGroup


I use ngx formly for building forms. What i need is to access form id inside some of the custom types i have. Basically i need to access form id in formGroup.

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({});

Input type component

@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?
    }

}

Solution

  • Inside a custom field type, you can access to the field and options instance where you can get the id, key...

    For your use case, you may rely on formState, so assign the formId to options.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);
      }
    }