Angular Error: Unable to access property 'users' on a null value

I am working on a component that takes in data through the @Input() decorator regarding a group. My objective is to generate a new array of objects during the initialization of the component based on the data from the group array. Below is the TypeScript component section:

import { Component, OnInit, Input } from '@angular/core';

import {Group} from "@models/group.model";

@Component({
  selector: 'app-group-admins',
  templateUrl: './group-admins.component.html',
  styleUrls: ['./group-admins.component.css']
})
export class GroupAdminsComponent implements OnInit {
  @Input() group: any = new Group();
  users: Array<object> = [];
  
  constructor() { }

  ngOnInit() {
    this.users = this.group.users.map((a: { user: number; permissions: number; }) => ({id: a.user, permissions: a.permissions}));
  }

  getUsers() {
    this.users = this.group.users.map((a: { user: number; permissions: number; }) => ({id: a.user, permissions: a.permissions}));
  }
}

Below are my Group and GroupUser models (if needed):

import {GroupUser} from "@models/group-user.model";

export class Group {
  group_name: string;
  type: string;
  avatar?: string;
  header?: string;
  address?: string;
  date?: string;
  city?: string;
  about?: string;
  verify_status?: string;
  site?: string;
  phone?: string;
  email?: string;
  web_site?: string;
  industry?: true;
  directions_list?: string;
  users: Array<GroupUser>
}

export class GroupUser {
  id?: number;
  user: number;
  permissions: string;
  confirmed?: boolean;
}

Here is the part of my parent TS component:

group = [];
ngOnInit() {
this.route.paramMap.subscribe(() => {
  this.id = this.route.snapshot.paramMap.get("id");
  this.groupService.getSpecGroup(this.id).subscribe(
    ((info) => {
      this.group = info;
    })
  );
});
}

And here is the HTML section:

 <app-group-admins [group]="group"></app-group-admins>

In summary, I am attempting to create a users array using ngOnInit, but I encounter an error

TypeError: Cannot read property 'users' of null
although everything works correctly when using the getUsers() function. Any assistance would be greatly appreciated.

Answer №1

Why not consider using a setter in the input field? If grouping is not necessary, there's no need to store data in an auxiliary variable.

  @Input() set group(value:Group){
    this.users = value && value.users ? value.users.map((a: { user: number; permissions: number; }) => 
          ({id: a.user, permissions: a.permissions}));
        :[];
  }
  users: Array<object> = [];
  constructor() { }

Answer №2

@Input() team: any = new Team();

I don't think that line is correct. The @Input decorator is typically used when passing data from a parent component to a child component and should not be re-initialized.

You could try implementing it like this instead:

@Input('team') team: Team;
ngOnInit() {
  console.log(this.team);
}

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

Combining Angular 4 with a pre-existing Spring Boot web app utilizing JSP components

Currently, I have a live Spring Boot web application that uses jsp and JavaScript. My goal is to gradually update existing pages with Angular when time allows. While I am new to Angular, most of the information I have come across suggests that it require ...

The Angular ngFor directive seems to be failing to display the items within the array, even though accessing the items directly by using array[index

I've come across a strange issue with a simple program I'm working on. I want to display a list of numbers using an array, but when I try to use *ngFor in Angular, the elements don't render. However, if I manually reference each element in t ...

Maintain the nullability of object fields when casting

I have been working on a type called DateToNumber that converts all the Date properties of an object to number. Here is what I have come up with so far: type LiteralDateToNumber<T> = T extends Date ? number : T extends Date | null ? number | nu ...

Apply a dynamic function to assign a background color to a specific class

Currently, I have a function called getBackground(items) that returns a background color from a JSON file list. Within my application, there is a component that automatically adds a class name (.item-radio-checked) when a user clicks on an item in the list ...

What is the best way to display a scrollbar at the bottom of the table while setting the table height to

After writing the css provided below, I noticed that it works fine on my laptop screen. However, when viewing it on a larger monitor, there is empty space at the end of the table. .wrapper{ width:auto; height: 500px; overflow-x: scroll; ...

"Enhance your development experience with the TypeScript definitions for the Vue 2 plugin

Currently, I am utilizing VSCode alongside TypeScript classes for developing Vue 2 components. You can check out more information at: vuejs/vue-class-component. Within my present project, I make use of plugins like vue-i18n for handling translations of la ...

Creating Angular models for complex nested JSON structures

I'm a beginner with Angular and I'm dealing with nested API responses from a Strapi application. I've set up a model using interfaces, but I'm having trouble accessing attributes from the product model when trying to access product data ...

Handling JSON Data in JavaScript

In the script below, I have a json object that is being processed: $http({ url: '/mpdValidation/mpdValidate', method: "POST", data: { 'message' : mpdData } ).then(function(response) { console.log(response.data ...

An issue was encountered when attempting to log out the user from Firebase

My website is built using the Ionic and Angular Frameworks along with Firestore database. The signout feature works as expected, but unfortunately, an error occurs when a user tries to sign out of their account. The error message: FirebaseError: Missing o ...

Setting up Node on a Ubuntu system

Currently, I am in the process of installing Node.js to run my Angular2 program. However, I encountered an error during the installation: npm WARN npm npm does not support Node.js v0.10.25 npm WARN npm You should probably upgrade to a newer version of nod ...

I am sorry, but it seems like there is an issue with the definition of global in

I have a requirement to transform an XML String into JSON in order to retrieve user details. The approach I am taking involves utilizing the xml2js library. Here is my TypeScript code: typescript.ts sendXML(){ console.log("Inside sendXML method") ...

Exploring Vue with Typescript - leveraging components without explicit definitions

Has anyone successfully used vue-instant component as a child component before? I'm having trouble adding components without definition. Could it be related to webpack config ignoring node_modules due to lack of type declaration? Here's the code ...

Next.js Troubleshooting: Unexpected Issue with 'use client' Triggering Error in React Client Component

Keeping it simple, here is a useState function that I am using: 'use client' import {useState} from 'react'; const Home = () => { const [fruit, setFruit] = useState('apple'); return ( & ...

Adjust ion-select label width across the entire screen in Ionic version 6

I recently began working on a fresh project using Ionic v6. As part of the development, I included a basic ion-select element in my HTML code: <ion-item> <ion-select placeholder="Select Option"> <ion-select-opti ...

Resolve the issue pertaining to the x-axis in D3 JS and enhance the y-axis and x-axis by implementing dashed lines

Can anyone assist with implementing the following features in D3 JS? I need to fix the x-axis position so that it doesn't scroll. The values on the x-axis are currently displayed as numbers (-2.5, -2.0, etc.), but I want them to be shown as percentag ...

Can you explain the distinction between the navigate function and routerLink feature in Angular 2?

As I go through the official Angular 2 tutorial, I noticed that it demonstrates using the navigate function in a way similar to routerLink. Can you explain the differences between these two methods and when it is best to use each? this.router.navigate([ ...

The deployment on Heroku is encountering issues due to TypeScript errors related to the MUI package

As someone relatively new to TypeScript and inexperienced in managing deployments in a production setting, I've been working on a project based on this repository: https://github.com/suren-atoyan/react-pwa?ref=reactjsexample.com. Using this repo has a ...

Difficulty arises when attempting to load Silverlight within an Angular2 component

Issue with Silverlight Component Loading When embedding and loading the Silverlight.xap file directly inside an HTML page, everything works perfectly. However, when we move the same code inside a component, the Silverlight content fails to load. Interest ...

Issues with Angular route links not functioning correctly when using an Array of objects

After hard coding some routerLinks into my application and witnessing smooth functionality, I decided to explore a different approach: View: <ul class="list navbar-nav"></ul> Ts.file public links = [ { name: "Home&quo ...

The form data consistently replaces existing values with each new entry added

I am struggling to persist all the form values that are entered in my component using local storage. Despite setting and pushing the form values, I noticed that each time I push the data, it replaces the previously entered form data. My goal is to retain a ...