Utilizing Angular 4: Incorporating an array of strings into checkboxes within reactive forms

I am trying to display checkboxes for my user roles:

For example, I have two user roles: 1. Admin 2. Employee

I have an array of roles in the userObject:

user={
        "name":"Bhushan",
        "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="85e7edf0f6ede4ebc5fce4edeaabe6eae8">[email protected]</a>",
        "roles":['Admin','Employee']
    }
    

I want to use a reactive form to populate this model into a form. I want to populate the roles array into read-only checkboxes i.e. when the form loads, the user can edit the name & email but checkboxes will show 'admin' toggled if the user has an admin role or untoggled if he is not an admin. The same can be said for the employee role.

So far I have tried the following:

<form [formGroup]="userForm" (ngSubmit)="onSubmit()" novalidate>
        <div style="margin-bottom: 1em">
            <button type="submit" [disabled]="userForm.pristine" class="btn btn-success">Save</button> &nbsp;
            <button type="reset" (click)="revert()" [disabled]="userForm.pristine" class="btn btn-danger">Revert</button>
        </div>
        <div class="form-group">
            <label class="center-block">Name:
                <input class="form-control" formControlName="name">
                </label>
        </div>
        <div class="form-group">
            <label class="center-block">Email:
                <input class="form-control" formControlName="email">
                </label>
            </div>
            <div class="form-group" *ngFor="let role of roles;let i=index">
                <label>
                    // I tried this, but it doesn't work
                    <!--<input type="checkbox" [name]="role" [(ngModel)]="role">-->
                        {{role}}
                </label>
            </div>
    </form>

    <p>userForm value: {{ userForm.value | json}}</p>
    

Any suggestions?

Answer №1

To implement this functionality, consider constructing a form with the roles stored in an array:

this.userDataForm = this.fb.group({
  name: [this.user.name],
  roles: this.fb.array(this.user.roles || [])
});

// Optionally, assign controls to variables for easy reference
this.nameControl = this.userDataForm.controls.name;
this.rolesControl = this.userDataForm.controls.roles.controls;

The template's roles array could be defined as follows:

roles = ['Admin', 'Employee','Some role 1', 'Some role 2']

In the iteration within the template, compare each role from the roles array to the corresponding value in the form array to check and set its status accordingly. Ensure to use the safe navigation operator to prevent errors when accessing non-existent indexes:

<div class="form-group" *ngFor="let role of roles; let i=index">
  <input [checked]="role == rolesControl[i]?.value" 
     [disabled]="true" type="checkbox">{{ role }}
</div>

See Demo

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

validation of dialog forms

Is there a way to trigger the $("#form").validated() function from the ok button in a jquery-ui-dialog? Please note that I would prefer not to use a submit button within the form. ...

Tips for preventing the repetition of values when dynamically adding multiple values to a text box using JavaScript

I am working on a function that adds multiple unique values to a hidden field. It is currently functioning correctly, but I want to ensure that the values added to the hidden field are unique and not duplicated if entered more than once. The select box wh ...

What is the process for generating the string HttpContext.GetGlobalResourceObject("languagetext","PersonalReportFrench") using C#?

I have a hardcoded JavaScript value in my aspx page that is currently functioning. PersonalReportLink.innerHTML = '<%=(String)HttpContext.GetGlobalResourceObject(@"languagetext","PersonalReportFrench")%>'; Now I want to make it dynamic. H ...

Leveraging an array with a switch() function in JavaScript

I am currently working on creating a simplified poker game using JavaScript. I have documented all potential card combinations that a player may have in their hand, organized by their value. Here's an example: switch(sortedHand) { //Pair ...

Creating circular patterns with looping on a canvas

My goal is to draw circles in a loop, but when I execute my code, I am encountering an unexpected result: The intention is to simply draw 3 circles in random positions. Here is my current code: for (var i = 0; i < iloscU; i++) { ctx.strokeStyle = ...

Increasing the size of elements with jQuery animate method

I've been utilizing the animate function in jQuery to dynamically resize a content area upon hovering over the element. Although the script is functioning correctly, I'm facing a challenge in preventing the script from resizing the content multi ...

What methods does JUMflot use to update points or select items? Interested in adding objects to an array and redrawing them without altering the original item

My goal is to use a button to push a line into an array and have JUMflot redraw those lines without affecting the original line being pushed in. Initially, I attempted this using the following code snippet (the generator ID represents the button and optio ...

Creating custom errors in Node.js is a powerful tool that can enhance the robustness and functionality of your applications. One common

I'm trying to create custom error objects in Node using Error as the prototype, and then send these errors back to the client using express's res.json() method. I am able to set the properties of a custom error instance, but when I use res.json() ...

Setting a default action for an Ext.Ajax.request error situation

In my application, I frequently make ajax requests using the Ext.Ajax.request method. Often, I find myself skipping error handling for failed requests due to time constraints or lack of interest in implementing fancy error handling. As a result, my code us ...

Determining the value of an element by examining the clicked element

My goal is to determine the remaining balance in my cart based on the selected item. Let's say I have 3 items in my cart, and I choose one that costs $100. Previously, I stated that I had a total of $300. In my HTML code, there are elements with IDs ...

Show a modal confirmation box in a JsonResult response from the controller based on a specific condition

Hello everyone, I am facing a unique situation: In my current view, there is a save button that serializes a form and sends it via Ajax to a JsonResult in the Controller. Within this JsonResult method, I am performing add/edit operations on tables in the d ...

Utilizing Template Literals within Typescript

Currently, I am facing a challenge with retrieving a variable from an object. cell: (row: any) => `${row.testcolumn}` The issue arises because I do not know the value of 'testcolumn' in advance since this process is dynamic. Despite my attem ...

Personalized program name appears when CTRL key is pressed

How can I create a custom title that only appears when the CTRL button is pressed? Example: Normally, the title will not display when the mouse hovers over it. However, if the user holds down the CTRL button while hovering over the title, it will appear. ...

Subtracted TypeScript concept

Is it possible to create a modified type in Typescript for React components? import {Component, ComponentType} from 'react'; export function connect<S, A>(state: () => S, actions: A){ return function createConnected<P>(componen ...

What is the process for integrating TypeScript into my current Vite (React) project?

Recently, I encountered an issue with my existing React app created using Vite. Initially, I used the React template in Vite by running the command: yarn create vite my-react-app --template react As the project evolved, I decided to introduce TypeScript f ...

Invoke the function once the database information has been retrieved

I am new to Node.js and I am attempting to execute a function after running a select query using the code below: private displayUserInfo(): any { let connect = this.connect(); connect.connect(function(err: any) { if (err) throw err; ...

Preventing Vue.js from triggering watch on initial load

I need to implement a feature where a button is initially disabled and only becomes enabled when the input value is changed. To achieve this, I am using a boolean flag that is set to true by default and turns false only when the input changes. The v-model ...

What is the best way to dynamically retrieve the field name from a JSON object using JavaScript?

Upon retrieving data from an API, I am interested in obtaining more detailed information from each field within the object, such as Name, Number, Select, and so forth. An issue that arises is that the field names can be altered on the server side; meaning ...

Using Tailwind classes as a prop functions correctly, however, it does not work when directly applied

Here's a component snippet I'm working on: export const TextInput = ({ label, wrapperClassName = "", inputClassName = "", labelClassName = "", placeholder = "", ...props }: InputProps & Fiel ...

Upon updating my application from Angular 14 to 16, I encountered an overwhelming number of errors within the npm packages I had incorporated

After upgrading my angular application from v14 to v16, I encountered numerous peer dependencies issues, which led me to use the --force flag for the upgrade process. However, upon compiling, I am now faced with a multitude of errors as depicted in the scr ...