Creating optional nested formgroups in Angular 2

Discussão em 'Angular' iniciado por Tim Dean, Outubro 29, 2024.

  1. Tim Dean

    Tim Dean Guest

    I am trying to implement a model-driven form in Angular 2. The structure of my data model is as follows:

    archive (FormGroup)
    name (FormControl)
    description (FormControl)
    connection (FormGroup)
    url (FormControl)
    authentication (FormGroup)
    username (FormControl)
    password (FormControl)


    Within this data model, the top-level name is required but the description field is optional. I can apply a required validator to name, and omit a validator from description.

    For the connection, I want it to be optional but if a connection is present its URL becomes required. Similarly for the authentication model of the connection: It is optional but if present the username and password would be required.

    I am trying to understand how to set up validators to enforce these rules. I have tried just omitting any validators from the connection form group, but that seemed to be requiring me to have a connection. I've seen online tutorials explaining how to implement custom validation on a nested form groups but nothing that describes how to make the entire nested formgroup optional.

    Is there a straightforward way to implement this model with Angular 2 FormGroup?

    Continue reading...

Compartilhe esta Página