How to dynamically build an Angular FormGroup based on an asynchronous condition and adjust...

Discussão em 'Angular' iniciado por AlejoDev, Novembro 2, 2024.

  1. AlejoDev

    AlejoDev Guest

    I’m working on a form in Angular where I need to dynamically build a FormGroup based on a condition that is retrieved asynchronously through an effect. The condition (sameServices) determines if an additional field, addressComplement, should be included in the form and be required.

    Here is my code:

    constructor(private shared: Shared) {
    effect(() => {
    this.business = this.shared.getBusiness();
    });

    if (this.business.sameServices) {
    this.branchDataForm = new FormGroup({
    address: new FormControl('', [Validators.required, Validators.minLength(3)]),
    addressComplement: new FormControl('', [Validators.required, Validators.minLength(3)]),
    });
    } else {
    this.branchDataForm = new FormGroup({
    address: new FormControl('', [Validators.required, Validators.minLength(3)])
    });
    }
    }


    My issues are:

    The constructor does not wait for the effect to complete before executing the conditional.

    If I place the conditional inside the effect, the HTML fails, indicating that it cannot find the controls since they are not yet defined at the time of template rendering.

    I need the form to be valid only if the required fields are present and meet their validation rules based on the condition (sameServices).

    Question

    What would be a clean and efficient way to build a FormGroup in Angular based on an asynchronous condition, dynamically adding or removing controls and their validators without cluttering the HTML with conditionals? Are there best practices for handling this type of scenario in Angular?

    Continue reading...

Compartilhe esta Página