0

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

why in ngAfterViewInit and not in e.g. ngOnInit? how to handle initial value that is not emitted from valueChanges?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.