Loop through all form controls in formgroup in reactive form

Поділитися
Вставка
  • Опубліковано 26 жов 2024
  • In this video we will discuss, how to loop through all form controls in a formgroup including nested form groups in a reactive form.
    Healthy diet is very important for both body and mind. We want to inspire you to cook and eat healthy. If you like Aarvi Kitchen recipes, please support by sharing, subscribing and liking.
    / @aarvikitchen5572
    Text version of the video
    csharp-video-tu...
    Slides
    csharp-video-tu...
    Angular 6 Tutorial
    • Angular 6 tutorial for...
    Angular 6 Tutorial Text Articles & Slides
    csharp-video-tu...
    Angular, JavaScript, jQuery, Dot Net & SQL Playlists
    www.youtube.co...
    Understanding this technique is very useful, as it can help us perform the following on all the form controls in a reactive form
    1. Reset form controls
    2. Enable or disable all form controls or just the nested formgroup controls
    3. Set validators and clear validators
    4. Mark form controls as dirty, touched, untouched, pristine etc.
    5. Move validation messages and the logic to show and hide them into the component class from the view template.
    Here is what we want to do : Loop through each form control in a form group including nested form groups and log the form control key and value to the console.
    logKeyValuePairs(group: FormGroup): void {
    // loop through each key in the FormGroup
    Object.keys(group.controls).forEach((key: string) = {
    // Get a reference to the control using the FormGroup.get() method
    const abstractControl = group.get(key);
    // If the control is an instance of FormGroup i.e a nested FormGroup
    // then recursively call this same method (logKeyValuePairs) passing it
    // the FormGroup so we can get to the form controls in it
    if (abstractControl instanceof FormGroup) {
    this.logKeyValuePairs(abstractControl);
    // If the control is not a FormGroup then we know it's a FormControl
    } else {
    console.log('Key = ' + key + ' && Value = ' + abstractControl.value);
    }
    });
    }

КОМЕНТАРІ • 12