What is the process for obtaining a nested FormControl?

Below is the structure of my form:

form = new FormGroup({
  name: new FormControl('', Validators.required),
  comment: new FormControl(''),
  endpointsPermissions: new FormControl({
    read: new FormControl(null),
    write: new FormControl(null)
  }),
  exportDefinitionsPermissions: new FormControl({
    read: new FormControl(null),
    write: new FormControl(null)
  }),
  sourcesPermissions: new FormControl({
    read: new FormControl(null),
    write: new FormControl(null)
  })
});

When trying to implement it in my HTML file, I used the following code snippet:

<mat-form-field appearance="fill" fxFlex="100">
    <mat-checkbox [formControl]="form.get('endpointsPermissions').value.read">{{"ROLES.READ" | translate}}</mat-checkbox>
</mat-form-field>

However, I encountered some errors:

control.registerOnChange is not a function

mat-form-field must contain a MatFormFieldControl.

Can someone guide me on how to correctly use [formControl] with nested FormControls?

Answer №1

If you're having trouble getting mat-checkbox to work inside mat-form-field, take a look at this resource to find out which elements are compatible with mat-form-field: https://material.angular.io/components/form-field/overview

For nested forms, the recommended approach is as follows:

form = new FormGroup({
        name: new FormControl('', Validators.required),
        comment: new FormControl(''),
        endpointsPermissions: new FormGroup({
            read: new FormControl(null),
            write: new FormControl(null)
        }),
        exportDefinitionsPermissions: new FormGroup({
            read: new FormControl(null),
            write: new FormControl(null)
        }),
        sourcesPermissions: new FormGroup({
            read: new FormControl(null),
            write: new FormControl(null)
        })
    });

Additionally, make sure to structure your HTML like this:

<div fxLayout="column" fxFlex formGroupName="endpointsPermissions">
        <h2 mat-dialog-title>Permission</h2>
        <!-- Endpoints -->
        <div fxLayout="row" fxFlex fxLayoutGap="16px">
            <span>Endpoints Permission</span>
            <mat-checkbox matInput formControlName="read">Read</mat-checkbox>
        </div>
    </div>

Answer №2

With the assistance of Eliseo, this implementation is now functioning:

form = new FormGroup({
    name: new FormControl('', Validators.required),
    comment: new FormControl(''),
    endpointsPermissions: new FormGroup({
        read: new FormControl(null),
        write: new FormControl(null)
    }),
    exportDefinitionsPermissions: new FormGroup({
        read: new FormControl(null),
        write: new FormControl(null)
    }),
    sourcesPermissions: new FormGroup({
        read: new FormControl(null),
        write: new FormControl(null)
    })
});
<mat-checkbox [formControl]="form.get('endpointsPermissions.read')">{{"ROLES.READ" | translate}}</mat-checkbox>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a problem during the installation process of cldr

GET `https://github.com/unicode-cldr/cldr-units-modern/archive/36.0.0.zip` Uh oh! There was an error while making the request. The error mentioned above occurs when attempting to: npm i cldr-data We have been using an Angular project for quite some time ...

"How to automatically populate an input field with a value when the page loads in an

I need assistance with setting the input value to 1 when the page is loaded, but for some reason, it remains empty. Can someone help me troubleshoot this issue? <tr *ngFor="let item of cartItems; let i=index"> <td class="cart_pr ...

How can I access properties of generic types in TypeScript?

Converting the generic type to any is a valid approach (The type E could be a typescript type, class, or interface) of various entities like Product, Post, Todo, Customer, etc.: function test<E>(o:E):string { return (o as any)['property' ...

Issue detected: No NgModule metadata was located for 'AppModule' in Angular version 6.1.0

app.module.ts Check out the code snippet below which defines AppModule for an Angular application: import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule } from ...

Can optional parameters be used to restrict TypeScript overloads in any way?

My objective is as follows: interface ColorRgb { red: number; green: number; blue: number; } function rgbToHex(red: ColorRgb, green?: undefined, blue?: undefined): string function rgbToHex(red: number, green: number, blue: number): string function r ...

Enhancing menu item visibility with Typescript and Vue.js 3: A step-by-step guide

How can I dynamically highlight the active menu item in my menu? I believe that adding v-if(selected) and a function might be the way to go in the first template. <template> <MenuTreeView @selected='collapsedMenuSelected' :items=&apo ...

What is preventing the combination of brand enums in Typescript 3?

Utilizing brand enums for nominal typing in TypeScript 3 has been a challenge for me. The code snippet below demonstrates the issue: export enum WidgetIdBrand {} export type WidgetId = WidgetIdBrand & string; const id:WidgetId = '123' as Wi ...

Unable to retrieve this information within an anonymous function

I am currently working on converting the JSON data received from an API interface into separate arrays containing specific objects. The object type is specified as a variable in the interface. Here is the interface structure: export interface Interface{ ...

Exploring the process of selecting checkboxes in Angular 6

I'm currently learning Angular 6 and I have a requirement to mark checkboxes based on specific IDs from two arrays: this.skillArray = [ {ID: 1, name: "Diving"}, {ID: 2, name: "Firefighting"}, {ID: 3, name: "Treatment"}, ...

Checking if a specific component element is present in the DOM using Jasmine and Angular

Greetings Stack Overflow Community, I've encountered a challenge while attempting to write a basic Jasmine Unit Test in Angular 5 to confirm the presence of an element in the DOM for components. I have successfully tested standard HTML elements like ...

Tips for importing a module from a typescript file into a Jest test file

My current setup involves using jest for testing my typescript codes. import ClassA from '../classA'; jest.mock('../classA'); However, when I try to import a class from my classA.ts file, an error is thrown by jest: export default ...

What could be the reason for the variable's type being undefined in typescript?

After declaring the data type of a variable in TypeScript and checking its type, it may show as undefined if not initialized. For example: var a:number; console.log(a); However, if you initialize the variable with some data, then the type will be display ...

Why am I struggling to show the success message on my basic CRM Angular web application?

I'm facing an issue in my Basic Angular app where the success message is not being displayed even after writing the correct code. 1)app.component.html <h1 class="c1">{{title}}</h1> <div *ngIf="success_msg;" style=&q ...

Leveraging dependency injection in Angular 2+ with pre-loaded models

I desire the ability to create an instance of a model using a constructor while also providing injected services to that model. To clarify, I envision something like this: var book = new Book({ id: 5 }); // creates instance, sets id = 5 book.makeHttpCa ...

The absence of definition for onSubmit is causing an issue in Angular 6

I am encountering an issue with validating the sign-in form as it is showing an error stating onSubmit is not defined. Below is the code snippet: import { Component, OnInit } from '@angular/core'; import { FormArray, FormControl, FormGroup, Vali ...

Why is my terminal showing certain output when I execute the command npm start?

I have a burning question. Upon running npm start in angular2, what exactly am I witnessing on my terminal screen? Where is this information originating from? I'm referring to: [1] No detection of a `bs-config.json` or `bs-config.js` override file. D ...

When a file is modified in Angular, it triggers an error prompting the need to restart the 'npm' service

Whenever I make changes to a file in my Angular application, I encounter the following error: ERROR in ./src/app/@theme/components/auth/index.js Module build failed: Error: ENOENT: no such file or directory, open 'C:\Dev\Ng\ngx-a ...

Having trouble with Angular 2 forms even after ensuring all validations are in place?

In my component, I have three input fields that are all required. I have added the 'required' attribute to each input element and placed them all within a form tag. When the button is clicked, I need to send the values of these 3 fields to a web ...

Can you guide me on how to generate a personalized stamp within the Angular component using Grapecity GcPdfViewer?

When a Pdf is opened in the GcPdfViewer by the User, they are required to stamp the Pdf with an image located in the src/assets folder. However, the example provided on this webpage is not functioning correctly. Can anyone offer me a functioning example? ...

Leveraging the typeof Operator within a Class

How can we utilize typeof in order to specify the type of a class property? Take a look at both examples below, where example A works but example B does not. A) Works outside class const data: {age:number, name:string} = {age:10, name:'John'}; c ...