What is the best way to add a new item to an array with no elements?

I have a group of students that I display using the *ngFor directive. The list of students is passed from the parent component. When the student list is empty, I still want to show an empty row on the component. Here is the array:

 @Input() studentList: Student[] = []; //child property

And in the parent component:

 get studentList(): Student[] {      //parent property
      const arr: Array<Student> = new Array<Student>();
if (getStudents()){
      arr=getStudents();
}
else{
      arr.push(new Student());
      return (arr);
    }
  }

The getStudents() method is just a mock method that returns null. The Student class has properties such as idNumber and studentName. However, if the array is empty, the *ngFor directive does not display any rows.

Answer №1

In this scenario, a possible solution would be to utilize

*ngIf=studentList.length === 0 to display an empty row.

*ngIf=studentList.length > 0 to display data when available.

Answer №2

If you're looking for a solution, consider using the following code snippet:

fetch studentData(): Student[] {
    const list: Array<Student> = [];
    if (list.length){
       list = retrieveStudents();
    } else{
      list = [new Student()];
    }
    return list; // don't forget to return it.
}

Answer №3

To properly initialize the Student as an empty array:

get studentList(): Student[] {      //parent property
      const arr: Student[] = []
if (getStudents()){
      arr = getStudents();
}
else{
      arr.push(new Student());
      return arr;
    }
  }

Answer №4

To implement a similar layout in your HTML file, consider the following code snippet:

<table>
<thead>
------
</thead>
    <tbody>
    <tr *ngFor="person of people">
    </tr>
    <tr *ngIf="people.length==0">
    </tr>
    </tbody>
</table>

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

Unable to receive any feedback when utilizing takeWhile in Angular 6 for continuously polling an API via HTTP requests

I am currently working with a client API that I need to continuously poll until it returns a successful result. The API response is in JSON format and looks like this: { "count": 0, "meta": { "status": "PENDING", "total": 3185, "completion_per ...

Angular 7: Unable to connect with 'messages' because it is not recognized as a valid attribute of 'message-list'

Currently, I am embarking on an Angular journey to develop a hobby chat project using Angular 7 for educational purposes. My main hurdle lies in comprehending modules and components, which has led me to encounter a certain issue. The Challenge In the tut ...

Determine whether an element is visible following a state update using React Testing Library in a Next.js application

I'm looking to test a NextJS component of mine, specifically a searchbar that includes a div which should only display if the "search" state is not empty. const SearchBar = () => { const [search, setSearch] = useState(""); const handleSear ...

Setting "pathMatch" to "full" on a route with an empty path results in a blank view being displayed

I am working with different routes in my project: In the app-routing.module.ts file: [ ... { path: "", loadChildren: () => import("./tabs/tabs.module").then(m => m.TabsPageModule), // "pathMatch": "full", }, ...

New Update in Typescript 4.9: The type 'NonNullable<K>' could potentially represent a primitive value, which is not allowed as the right operand in the 'in' operator. Error code: 2638

Amidst the changes in Typescript 4.9, there are some updates to how the in operator operates. Given the code snippet below, what approach can I take to convince tsc that id is not just a primitive value? export type KeyOrId = | { key: string; ...

Troubleshooting problem with event triggering in Angular's ngSelect dropdown menu items

Hello, I am currently utilizing ngSelect but encountering an issue. Whenever a user hovers over an option in ngSelection, I would like to trigger an event that is created in my typescript file. I am using Angular 13, so I am unsure how to achieve this. Is ...

Error TS2769: Extending styles with props on base style in React Styled-components TypeScript results in a compilation error

I've been attempting to expand a base style to other styled components and encountering a TypeScript error. While I could achieve this in pure JavaScript, I'm facing difficulties in TypeScript. Base file _Modal.ts import styled from 'styled ...

Generating ambient module declarations in Typescript for distribution on NPM

Seeking advice on generating TypeScript ambient module declarations for a node (commonjs) npm package being developed in TypeScript. Encountering confusion around the proper method to have TypeScript create these ambient module declarations for node / comm ...

TS2339 error: Transitioning from JavaScript to TypeScript bug

Struggling with errors in the TypeScript implementation, specifically: Error TS2339: Property 'style' does not exist on type 'Element'. (dashboard.component.ts line 49) Error TS2339: Property 'textContent' does not ...

Problems encountered while trying to install the angular2-meteor package using npm

Attempting to kick off a fresh angular2-meteor project with the command: npm install angular2-meteor --save Encountering a slew of red errors (shown below) and I'm puzzled by their significance. Already executed npm install npm -g and npm ...

Selecting only the month and year with the v-date-picker

I am looking for an alternative approach using the v-date-picker component. My requirement is to allow users to only select the year and month, and then close the date picker menu automatically. Below is an example of my HTML code, but I am open to using ...

Ways to trigger an event based on the outcome of a pop-up window

In my current project, I am working on a component that includes three buttons: two default options and an additional modal dialog option for more advanced choices. When one of the default buttons is clicked, the component emits an event based on the selec ...

Angular Collapsible Panel showcasing brief summary

I am struggling to implement an accordion feature in Angular that displays a brief description of the content initially, and when clicked on, reveals the full description. I need to truncate the content and display it in the header. Despite my attempts, I ...

Combine various arrays of objects into one consolidated object

Problem: There are untyped objects returned with over 100 different possible keys. I aim to restructure all error objects, regardless of type, into a singular object. const data = [ { "type":"cat", "errors" ...

A guide on obtaining the ReturnType within a UseQuery declaration

I am currently working on building a TypeScript wrapper for RTKQ queries that can be used generically. I have made progress on most of my goals, but I am encountering an issue with determining the return type for a generic or specific query. I have shared ...

Steps to retrieve the HTTP response from an ngxs action

Is it possible to receive an HTTP response in a component without storing the result? I want to use the response directly in the component without saving it. How can I achieve this? @Action(GetNovels, { cancelUncompleted: true }) getNovels(ctx: StateCont ...

How can the fields and methods in an Angular module enhance its usability?

Are the fields and methods of an Angular module used for usability purposes? If they are, when would it be beneficial? ...

Angular2 ERROR: Unhandled Promise Rejection: Cannot find a matching route:

I'm facing an issue with my Angular2 application while utilizing the router.navigateByUrl method. Within my component, there is a function named goToRoute, structured as follows: router.goToRoute(route:string, event?:Event):void { if (event) ...

Updating the useState() function in React when the value changes can be done by utilizing the

I'm struggling to update the count value in my React project. Within my dynamic set, I aim to display the size of the set whenever it changes! My goal is to continuously update the count variable to match ratedSet.size whenever the set's size c ...

Why are my Bootstrap panels not showing up in my Angular4 app, even though the navbar and footer are working

Currently, I am developing an angular4 application with an app.component.html that is structured as follows: <app-nav></app-nav> <div class="container"> <div class="panel panel-primary"> <div class="panel-heading"> ...