user21636825
user21636825

Reputation: 33

how to update form fields by condition in dynamic form in angular?

I have a dynamic form in Angular and I want to change form fields by condition, for example I want to show Accept terms field only when the user selects India as a country. Example: The user selects "India" as a country and then the form changes because of this input. Form fields should be updated on triggers like that.

How can I do this?

The list of fields in my form is as follows:

 regConfig: FieldConfig[] = [

    {
      type: 'input',
      label: 'Username',
      inputType: 'text',
      name: 'name',
      validations: [
        {
          name: 'required',
          validator: Validators.required,
          message: 'Name Required',
        },
        {
          name: 'pattern',
          validator: Validators.pattern('^[a-zA-Z]+$'),
          message: 'Accept only text',
        },
      ],
    },
    {
      type: 'input',
      label: 'Email Address',
      inputType: 'email',
      name: 'email',
      validations: [
        {
          name: 'required',
          validator: Validators.required,
          message: 'Email Required',
        },
        {
          name: 'pattern',
          validator: Validators.pattern(
            '^[a-z0-9._%+-]+@[a-z0-9.-]+.[a-z]{2,4}$'
          ),
          message: 'Invalid email',
        },
      ],
    },
    {
      type: 'date',
      label: 'DOB',
      name: 'dob',
      validations: [
        {
          name: 'required',
          validator: Validators.required,
          message: 'Date of Birth Required',
        },
      ],
    },
    {
      type: 'select',
      label: 'Country',
      name: 'country',
      value: 'UK',
      options: ['India', 'UAE', 'UK', 'US'],
    },
    {
      type: 'checkbox',
      label: 'Accept Terms',
      name: 'term',
      value: true,
    },
    {
      type: 'button',
      label: 'Save',
    },
  ];

stackblitz

Upvotes: 0

Views: 329

Answers (1)

Shifenis
Shifenis

Reputation: 1125

You can easily check the country whenever the select has been changed.

ngAfterViewInit() {
   this.form.form.valueChanges.subscribe((change) => console.log(change));
}

At this point, you can remove the checkbox from the default configuration and add it only when the value meets the criteria

Upvotes: 1

Related Questions