To tally and showcase the existing strings within an array

I am working with an API named teachers that has the following structure:

Teachers:

[
  {
    "id": "01",
    "teacherName": "Binky Alderwick",
    "studentIds": [
      "010",
      "024",
      "031"
    ],
    "totalStudents":"20"
  },
  {
    "id": "02",
    "teacherName": "Basilio Gregg",
    "studentIds": [
      "041",
      "075"
    ],
     "totalStudents":"10"
  },
  {
    "id": "03",
    "teacherName": "Binky Alderwick",
    "studentIds": [
      "075",
      "048",
      "035"
    ],
     "totalStudents":"40"
  }
]

The student data in the JSON file contains multiple strings under the studentIds property within an array.

I want to count these strings and compare them with the totalStudents property in order to display the available students as shown here: https://i.sstatic.net/9jTzb.png

Check out the StackBlitz Demo for more details.

Answer №1

Insert this code snippet into your html file

<h4>Educators</h4>
<div class="cust-detail" *ngFor="let educator of educators">
    <tr>
        <td>Name</td>
        <td>{{educator.educatorName }}</td>
    </tr>
    <tr>
        <td>Number of Students</td>
        <td>{{ educator.studentIds.length }}</td>
    </tr>   
    <hr>
</div>

If you prefer the updated format in the revised question, here is the modified version to use:

   <h4>Educators</h4>
    <div class="cust-detail" *ngFor="let educator of educators">
        <tr>
            <td>Name</td>
            <td>{{educator.educatorName }}</td>
        </tr>
        <tr>
            <td>Number of Students</td>
            <td>{{ educator.studentIds.length }}/{{educator.totalStudents}} </td>
        </tr>   
        <hr>
    </div>

Answer №2

If you want to find out how many items are in an array, you can use this method:

<h4>Educators</h4>
<div class="info" *ngFor="let educator of educators">
    <tr>
        <td>Name</td>
        <td>{{educator.educatorName }}</td>
    </tr>
    <tr>
        <td>Number of Students</td>
        <td>{{educator.studentIds.length}}</td>
        <td></td>
    </tr>   
    <hr>
</div>

Answer №3

For those looking to showcase the number of students enrolled, one can utilize the following code snippet within their template:

{{teacher.studentIds.length}}/{{teachers.totalStudents}}

Keep in mind that data-binding allows for easy access to information, enabling you to display a wide range of data as needed.

Answer №4

To enhance the teacher list, you can iterate through each teacher and create a new property called 'availableStudents' as a string. Set this property based on the number of student IDs in relation to the total students for that teacher.

for(let teacher of teacherList)
{
 teacher.availableStudents=`${teacher.studentIds.length}/{teacher.totalStudents}`}
}

Once added, you can easily access this information in your HTML code.

For better organization and readability, consider encapsulating this logic within a function like computeAvailableStudent. After fetching the list from the server, invoke this function to ensure your data is properly prepared for usage.

It's recommended to handle such computations in TypeScript files rather than directly in HTML for easier testing and maintenance.

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

Utilizing Angular 5 alongside the powerful ngx-cookie library and configuring it all within the system

Currently in the process of upgrading a project from AngularJS 1 to Angular 5. In need of a package for cookie manipulation, I came across ngx-cookie. However, facing a hurdle as I cannot alter systemjs.config.js as per the instructions provided, given t ...

Developing hybrid applications without using Angular or React

As a newcomer to Hybrid App Development, I recently created a website using core coding without frameworks like Angular or React. Now, my goal is to transform this website into a Hybrid App. However, I'm facing some lingering questions that I couldn& ...

Invoke a function within the embedded element

I currently have two components, known as app-student-list and app-student-detail. My goal is to incorporate the student-detail within the student-list in the following manner: Within app-student-detail.html: <p>Student Detail Component content go ...

Transforming TimeZone Date Object without Altering Time

I am looking to change the time zone of a date from one timezone to another. For example: "Sun May 01 2019 00:00:00 GMT+0530 (India Standard Time)" is the current date object. I want to convert this date based on a specific timeZone offset, let's say ...

Angular: Defining variables using let and var

When working with TypeScript and JavaScript, we typically use either let or var to declare a variable. However, in Angular components, we do not use them even though Angular itself uses TypeScript. For instance, export class ProductComponent implements OnI ...

Triggering createEffect in SolidJS with an external dependency: A guide

Is there a way to use an external dependency to trigger the createEffect function in Solid, similar to React's useEffect dependency array? I am trying to execute setShowMenu when there is a change in location.pathname. const location = useLocation() ...

Enhance the Angular version from 8 to 9

Looking to update my Angular version from 8 to 9 Visit this link: https://update.angular.io/#8.0:9.0l2, I am trying to execute the command : ng update @angular/core@8 @angular/cli@8 but encountering an error: The package "ng-push" has a conflicting peer ...

What is the best way to ensure that all function parameters using a shared generic tuple type have a consistent length?

Understanding that [number, number] | [number] is an extension of [number, ...number[]] is logical, but I'm curious if there's a method to enforce the length of tuples based on the initial parameter so that the second tuple must match that same l ...

The immutability of TypeScript's `as const` compared to JavaScript's Map object

Let's delve into a straightforward example: const simpleObject = { one: 'one', two: 'two', three: 'three' } Historically, pre ES2015 objects did not guarantee the preservation of key order upon retrieval. However, ...

"Encountering issues with npm installation while trying to set up Angular

Whenever I attempt to execute npm install, I encounter the following error message: npm ERR! node v0.12.12 npm ERR! npm v3.3.6 npm ERR! code ELIFECYCLE npm ERR! <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b4d5dad3c1d8d5c6 ...

One way in Angular to set a validator pattern regex that matches either one rule or the other, but

Trying to implement user range matching with angular validators, like shown in the image below: https://i.stack.imgur.com/zXHn3.png The goal is to validate against one of two range options using an angular pattern validator: 1-99 or 1,2,5,6,8, but not b ...

Deduce the property type by the existence of the value

Here's a situation I'm trying to address in a simple way: if the entity prop is present, I want the onClick callback to receive the entity string, otherwise it should receive nothing. type SnakeOrCamelDomains = "light" | "switch" | "input_boolean ...

Establishing a connection to an API with basic authentication in Angular 8 and Express JS

After setting up my angular 8 app and connecting it to an express API, I decided to run it locally for testing purposes. The front end of the app connects to http://localhost:4200/, while the backend connects to http://localhost:3000/. Additionally, I crea ...

Configuring a server-side rendered Angular application on Plesk hosting platform

After successfully setting up server side rendering in my Angular app using nguniversal on my local machine, I am now facing the challenge of implementing this on a remote server with Plesk. In my local environment, I can serve the files by running: npm r ...

Unpacking data types from an array of classes in TypeScript: A step-by-step guide

I am working on a function that takes an array or rest of Typescript classes as input and resolves, returning their instances. However, I'm struggling to ensure correct typing for it. If I take one class as an example: class Base { isBase = true ...

The functionality of anchor links becomes disrupted once the APK is finalized in Ionic/Angular2 development

After testing my application using Ionic View, everything was functioning properly. The links, which were implemented using anchor tags with normal href attributes in the HTML, were working as expected. However, when I built the application and clicked on ...

Using TypeScript, one can easily employ a jQuery element within Vue's 'data' option

Is there a way to store a reference of a jQuery element in the Vue 'data' object without causing TypeScript errors? Any suggestions on how to resolve this issue? [EDIT] I managed to work around the TypeScript error by setting a non-existing jQu ...

Steps to perform a task that relies on two observables

I'm currently working on a function that requires two responses from two separate asynchronous functions, both returning observables. 1. Func1 returns an observable 2. Func2 returns an observable These functions are independent and can be executed sep ...

Creating and accessing files within the `dist` folder in Angular 5: A comprehensive guide

After deploying my Angular 5 app to Cloud Foundry, a file named app-number-version is automatically generated in the dist folder with just the version number (e.g., "1.0.0"). My goal is to show this version number in the navigation bar of our app's H ...

What are the methods to alter validation for a Formfield based on the input from other Formfields?

My aim is to create a Form where input fields are required only if one or more of them are filled out. If none of the fields have been filled, then no field should be mandatory. I came across a suggestion on a website that recommended using "valueChanges" ...