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

Efficiently loading data in a table with a universal filter feature using Angular with PrimeNG

Recently, I managed to set up a datatable with the functionalities of both Lazy loading and global filter. Utilizing PrimeNG components for this implementation was a breeze. However, an issue surfaced where the global filter ceased to function when lazy lo ...

The custom css class is failing to be applied to a tooltip within Angular Material version 15

After updating Angular Material to version 15, I noticed that I can no longer apply custom coloring to the material tooltip. Here is an example code in .html: <button mat-raised-button matTooltip="Tooltip message" matTooltipClass="cu ...

Remove any objects with nil values from an array using filter and flatMap in Swift 4

I am populating a UICollectionView with results retrieved from a query. Occasionally, the records returned do not contain images. I want to exclude these objects completely. How can I avoid displaying results from a JSON query that do not include any imag ...

The source files are expected to be contained within the 'rootDir' directory, which is not located at 'c:/Users/hasit/Desktop/typescript/src'

Can someone assist me with separating the Src folder and public folder in my project? When I try to do it in the tsconfig.json file, I encounter this error: "'rootDir' is expected to contain all source files." I have followed instructions from a ...

Eliminate the alert message that appears when dynamically rendering a React styled component

When checking the browser console, I noticed a warning that reads as follows: react_devtools_backend.js:3973 The component styled.div with the id of "sc-dmRaPn" has been created dynamically. You may see this warning because you've called sty ...

Having difficulty sending a message from an AngularJS application to an Angular 10 application through an iframe

I have two applications running locally - one is an AngularJS application and the other is an Angular 10 application. I am trying to access a page from the Angular 10 application using an iframe and send a message to it from the AngularJS application. How ...

Certain textboxes within a Reactive Form in Angular 6 are experiencing issues with clearing properly

I am utilizing Angular 6 along with Reactive Forms to establish a timetable containing 2 sections. The location section includes origin and destination textboxes, while the trip section, nested within the schedule, also consists of origin and destination t ...

Risky assignment of an 'any' value" encountered while implementing react-transition-group in TypeScript

Encountering @typescript-eslint errors while implementing the Transition component from react-transition-group. Implemented the official React Transition Group example for JS in a TypeScript + ESLint project, resulting in the error message: Unsafe assignm ...

Tips for changing the color of an icon when clicking a button

How can I dynamically change the color of an icon when clicked? Would using ngClass be the most efficient approach for this task? Currently, I have assigned a class to my icon. <ion-card> <ion-row> <ion-col> < ...

Show a select element with choices that change depending on another select element

I am currently working on a select dropdown component that utilizes the @Input option variable. My goal is to have another instance of this component display options based on the selection made in the first instance. Any suggestions on how to make this h ...

Using TypeScript's `async await` within a nested function invocation

I am having trouble extracting the 'assigned suspect' from the callbacks, as it is showing up as undefined. Strangely, it works fine within an if statement. I believe the issue is related to the await/async functionality. Any assistance would be ...

I require the ability to identify and capture the ID of the button (touchable opacity) that has been

When trying to delete a selected button by obtaining its specific id, I am facing an issue where after the first execution, the id of the deleted item is retained instead of the newly selected one. I am in need of a solution that allows me to retrieve the ...

What sets apart the utilization of add versus finalize in rxjs?

It appears that both of these code snippets achieve the same outcome: Add this.test$.pipe(take(1)).subscribe().add(() => console.log('added')); Finalize this.test$.pipe(take(1), finalize(() => console.log('finalized'))).sub ...

Typescript input event

I need help implementing an on change event when a file is selected from an input(file) element. What I want is for the event to set a textbox to display the name of the selected file. Unfortunately, I haven't been able to find a clear example or figu ...

What is the best way to load a component every time the function is called?

Currently, I am utilizing Angular and endeavoring to create reusable actions such as bulk updates, deletes, and deactivations. I have incorporated all of these actions into another component and aim to use it as a generic method. This implies that I have ...

How can I convert single-element arrays into their individual elements?

When I imported a JSON document into a pandas dataframe using records = pandas.read_json(path), I encountered an unexpected issue. Some columns in the resulting "records" dataframe did not contain simple strings as anticipated. Instead, each cell in these ...

Creating a TypeScript declaration file for a singular module

Consider the following directory structure: src/ ├── foo.ts ├── bar.ts ├── baz.ts ├── index.ts If foo.ts, bar.ts, and baz.ts each export a default class or object, for example in foo.ts: export default class Foo { x = 2; } I ...

Converting JSON formatting from Object to Array: A Comprehensive Guide

Encountering another issue with changing the JSON array output. Struggling to figure out why it's not rendering the other files. Providing a clearer explanation below: In my code snippet, when I use data[name] = {, each return name is rendered into ...

The function is unable to access the 'FacebookAuthProvider' property as it is undefined

I'm having trouble using Angular Firebase to connect with Facebook. I keep encountering this error: AppComponent.html:2 ERROR TypeError: Cannot read property 'FacebookAuthProvider' of undefined at AuthService.signInWithFacebook (auth.servic ...

Nested loops seem to override previous results with the final output

I am attempting to iterate through an array of months nested within an array of 'years' in order to calculate a count for each month using a custom angular filter. Initially, I set up the structure I will be looping through in the first while loo ...