Is there a way for me to confirm the presence of a particular object within an array and return a true value

I am working on a form in Angular that includes checkboxes. I want to automatically check the checkbox if the user has a specific role.

Here is my current approach:

<form [formGroup]="rolesForm">
  <label 
    formArrayName="roles" 
    *ngFor="let role of rolesForm.controls['roles'].controls; let i = index"
  >
    <input 
      type="checkbox" 
      [checked]="checkIfTrue(role[i])"
      [formControlName]="i" 
    /> {{role[i].name}}
  </label>
</form>

This is part of the component:

roles: Role[] = [
  {
    uid: '456DNC',
    name: 'Admin'
  },
  {
    uid: '546DKZ',
    name: 'Member'
  },
  {
    uid: '741JXY',
    name: 'Guest'
  }
]

user: User = {
  uid: '123ABC',
  name: 'Steve',
  roles: [
    {
      uid: '456DNC',
      name: 'Admin'
    }
  ]
}

rolesForm: FormGroup;

ngOnChanges() {
  const formControls = this.roles.map(role => new FormControl(false));

  this.rolesForm = this.formBuilder.group({
    roles: new FormArray(formControls)
  });
}

checkIfTrue(role: Role) {
  return this.user.roles.find(role);
}

An error message I'm encountering is:

[object Object] is not a function at Array.find

In trying to resolve the issue, I experimented with using .indexOf() and .includes()

Answer №1

To ensure the proper functioning of the reactive form, it is recommended to set the value when constructing the form rather than relying on the [checked] property.

Visit this link for an example.

ngOnChanges() {
  const formControls = this.roles.map(role => new FormControl(this.checkIfTrue(role)));

  this.rolesForm = this.formBuilder.group({
    roles: new FormArray(formControls)
  });
}

checkIfTrue(role) {
  return this.user.roles.find(r => r.uid === role.uid);
}
<form [formGroup]="rolesForm">
  <label 
    formArrayName="roles" 
    *ngFor="let role of rolesForm.controls['roles'].controls; let i = index"
  >
    <input 
      type="checkbox" 
      [formControlName]="i" 
    /> {{roles[i].name}}
  </label>
</form>

Answer №2

When the indexOf() method does not find any elements, it returns -1. To handle this situation, you can use the following implementation:

return this.user.roles.indexOf(role) != -1

With this approach, the code will return true if the element is found using indexOf, and false if it is not.

You can include this logic in your checkIfTrue(role: Role) method

Answer №3

Nothing to worry about, just make this slight modification:

 validateRole(role: Role) {

   this.user.roles.find(element=>{
    if(element.name === role) {
       return true;
     }
     });
   }

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

The angular2-markdown module encounters errors

I am currently working on implementing a markdown editor in a form within my Angular2 project. To achieve this, I have installed the angular2-markdown module. However, I encountered an error when trying to use it, specifically: "marked" is not a function. ...

Issue with Material UI v5: "spacing" property not found on custom theme object

My current setup involves using version 5 of material ui, where I have customized a theme and applied it to all my components. However, when trying to add padding to a paper element in one of my components based on the theme, I encountered the following e ...

Iterating through a for loop in Angular2 to send multiple GET requests to a Django backend

Currently, I'm facing a challenge with performing multiple GET requests using Angular2 within a Django/Python environment. After successfully making an API request and retrieving a list of users to determine the current user's ID, I utilize a .f ...

How can I integrate React-Router Link as a component within Material-UI using Typescript?

Hey everyone, I've encountered an issue while trying to utilize Material UI's component prop to replace the base HTML element of a component. Error: The error message reads: Type 'Props' is not generic. This problem arises from the fo ...

The Angular2 app and NodeJs in the Docker container are unresponsive

After creating a new Angular2 app using angular-cli and running it in Docker, I encountered an issue where I could not connect to it from localhost. First, I initialized the app on my local machine: ng new project && cd project && "put m ...

REDUX: The dispatch function is failing to update the store

Working on a project developing a chrome extension that involves dispatching functions in popup.tsx. However, the store does not update when I try to dispatch. Interestingly, the same code works perfectly fine in the background page. Any suggestions on wha ...

Tips for creating an array in a <script> tag within an hbs view template

Currently, I am delving into the world of full stack web development with a focus on Node/Express. The project at hand is to create a voting app as part of a challenge from FreeCodeCamp, which you can find here. To display user votes in pie charts on the f ...

React/TypeScript - react-grid-layout: The onDrag event is fired upon clicking the <div> element

I am currently working on creating a grid with clickable and draggable items using the react-layout-grid component. However, I am facing an issue where the drag is instantly activated when I click on the item without actually moving the cursor. Is there a ...

JavaScript - Issue with retrieving object properties accurately

Here is a code snippet that I am working with: function retrieveObjects(name, data) { return data.filter(function(d) { return name.title == d.title; }).map(function(d) { return { "title": d.title, "sort": d. ...

Chunk loading in IE 11 has encountered an error

Having an issue with my website which is created using Angular 5. It seems to be malfunctioning in IE 11, and I am encountering the following error in the console: https://i.stack.imgur.com/Ek895.png Any insights on why my Angular code isn't functio ...

How to bring in images from the assets folder using React and Typescript

I'm facing an issue where direct image importing is working, but when using object types, it's not functioning properly. Why could this be happening? I am currently working with "react": "^16.12.0" and "typescript": "~3.7.2" // ./src/assets/baby ...

Heroku build is reporting that it cannot locate the `@types` in the package.json file

Encountered Heroku Build Error - TSError: ⨯ Struggling to compile TypeScript: - src/server.ts(1,38): error TS7016: File declaration for module 'express' not found. '/app/node_modules/express/index.js' is implicitly of type 'any&a ...

There seems to be an issue with loading fonts properly in the combination of Webpack and

I'm currently working on setting up the latest Angular2 with webpack without using the angular CLI. However, whenever I try to build my project, I keep encountering errors related to fontawesome fonts. Here's an example of the error message: ERR ...

Configuring ESLint, Prettier, and TypeScript in React Native: A Step-by-Step Guide

Could you provide guidance on setting up ESLint, Prettier, and TypeScript in React Native? I'm currently using absolute paths to specify components. Can you confirm if this setup is correct? tsconfig { "extends": "@tsconfig/react-n ...

Is it possible for a node and @angular/cli based application to function without an internet connection?

As a newcomer to the world of angular/cli and node, I am eager to build an application using Angular and deploy it to an environment where all external communication is blocked by a firewall. In this restricted setting, even accessing search engines is imp ...

How can I populate dropdown options from an API in a react JS project using typescript and react saga?

Check out my page, where I am trying to fetch brand options from an API. Below is the saga I have implemented: Action.tsx export const getBrandsForDropdown = (request: IPagination) => { return { type: actions, payload: request ...

The guidelines for implementing pipes in Angular 2

I am struggling with writing a pipe that should filter for both AUID and firstname. Unfortunately, it seems to only be working for the firstname. Can anyone help me figure out why? Below is the code snippet in question: return value.filter((searc ...

What causes a function loss when using the spread operator on window.localStorage?

I am attempting to enhance the window.localStorage object by adding custom methods and returning an object in the form of EnhancedStorageType, which includes extra members. Prior to using the spread operator, the storage.clear method is clearly defined... ...

Ionic 5 page div within ion-contents element is experiencing scrolling issues on iPhone devices

My application features a div element containing an ion-slides component. The ion-slides component houses several ion-slide elements that slide horizontally. Here is the relevant code snippet: <ion-content [scrollEvents]="true"> <div ...

Expand the HTTP Response interface with Typescript

Recently, I've been working on a piece of code that involves the axios library. Here's what I have so far: const BTrustURLResponse: Response = await axios.get(`${process.env.BTRUST_URL}/flow/${process.env.BTRUST_FLOWID}/link?callback_url=${callba ...