What could be causing my items to appear twice and as blank elements?

I'm feeling a bit lost here as to why my code isn't functioning correctly. For some reason, it's not displaying the predefined items that I've set up. Any guidance or assistance would be greatly appreciated. Dealing with Angular errors has been quite challenging for me lately, especially since I'm new to all of this. Thank you in advance for any help.

Let's start by looking at my HTML files:

---------------------------
<div class="row">
  <div class="col-xs-12">
    <div *ngIf="students">
      <ul *ngFor="let student of students" class="list-group">
        <li class="list-group-item">
          <h3>{{ student.studentname }}</h3>
          <h3>{{ student.studentsurname }}</h3>
          <h3>{{ student.studentnumber }}</h3>
        </li>
      </ul>
    </div>
  </div>
</div>

Now, onto my TypeScript file:

----------------------------------------------------
import { Component, OnInit, AfterViewInit, Input } from '@angular/core';
import { StudentService } from '../student.service';
import { Student } from '../student.model';

import { Component, OnInit, AfterViewInit, AfterViewChecked, Input, OnChanges } from '@angular/core';
import { StudentService } from '../student.service';
import { Student } from '../student.model';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-all-students',
  templateUrl: './all-students.component.html',
  styleUrls: ['./all-students.component.css']
})
export class AllStudentsComponent implements OnInit, AfterViewInit{

  constructor(private studentService: StudentService) { }
  studentSub: Subscription;
  students: Student[] = [];

  ngOnInit(): void {
    this.students = this.studentService.getStudents();
    this.studentService.studentChanged.next(this.students)
    this.studentSub = this.studentService.studentChanged.subscribe(
      (students: Student[]) => {
        this.students = this.studentService.getStudents();
      }
    )
  }

  ngAfterViewInit(){

  }
}

And finally, my Injectable script:

---------------------------------------------------
import { Injectable } from '@angular/core';
import { Student } from './student.model';
import { Subject } from 'rxjs';


@Injectable({
  providedIn: 'root'
})
export class StudentService {

  private students: Student[] = [
    new Student('Varughese', 'Mathew', 3459879),
    new Student('Sammy', 'Banamy', 3978462)
  ];

  studentChanged = new Subject<Student[]>()

  getStudent(index: number){
    return this.students[index];
  }

  getStudents(){
    return this.students.slice();
  }

  addStudent(student: Student){
    this.students.push(student);
    this.studentChanged.next(this.students.slice())
  }

  addStudents(students: Student[]){
    this.students.push(...students);
    this.studentChanged.next(this.students.slice())
  }
}

If anyone can offer some insights or solutions, I would be incredibly grateful.

Answer №1

Make sure to update the names to correspond with those in the student roster. If the class names do not match, the functionality will be compromised.

div class="row">
  <div class="col-xs-12">
<div *ngIf="students">
  <ul *ngFor="let student of students" class="list-group">
    <li class="list-group-item">
      <h3>{{ student.stname}}</h3>
      <h3>{{ student.stsurname }}</h3>
      <h3>{{ student.stnumber}}</h3>
    </li>
  </ul>
</div>

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

Press the damaged interior when looping through array elements in *ngFor, especially if they are generated from a function

When working with Plnkr, I encountered a peculiar edge case that seems to be related to the usage of pixijs or webgl. Interestingly, clicking on elements in the list works fine until you interact with pixijs by clicking the button, after which the click ev ...

Can you explain the significance of the symbol ! when declaring a variable in TypeScript?

Currently, I am delving into an Angular project and came across a peculiar line of code in the component.ts file provided by my instructor. @Input() public searchType!: string; This line resides within the OnInit() function of the component's TypeScr ...

Angular 6 - Resolving the Issue of 'Function calls are not supported in decorators' in Production Builds

Currently, I'm in the process of developing a cutting-edge Angular 6 application. However, as I was progressing with the development phase and tried to create a prod build using the following command: ng build --prod To my dismay, I encountered a pe ...

Loading game resources in advance for future or immediate utilization

I'm currently developing a game UI that involves a large number of image files, totaling around 30MB in size. I've been caching these images to the disk using service workers, but some of them are quite large at 3MB each. Even when they are retri ...

Typescript validation of tokens using Azure functions

Currently working on a website utilizing Azure Static Web App, where the login/registration is managed by Azure B2C. The backend API consists of typescript Azure functions integrated with Azure Static web app. Certain API calls can only be accessed when th ...

Angular 4 with Universal: Implementing 404 Status Code in Header for /404 Page Component

After researching and reviewing numerous StackOverflow inquiries, I have come to the conclusion that headers are derived from responses served by servers, making it a non-issue. I attempted to rectify the situation from my server.ts file but unfortunately ...

Ways to stop a ngFor loop in TypeScript

I'm currently working on a Hybrid app using Ionic-3. I have a function in my Typescript file that is being called from the Html, but it seems like the function is being executed multiple times causing my browser and application to hang. Below are the ...

Typescript: issue with type guard functionality not functioning properly

type VEvent = { type: "VEVENT"; summary: string; }; type VCalendar = { type: "VCALENDAR"; }; const data: Record<string, VEvent | VCalendar> = (...); array.map((id) => { return { id, title: dat ...

How to retrieve the current route name or URL in AngularDart5

Exploring the OnActivate feature in Angular docs, I am attempting to utilize it to dynamically update the UI based on the current route. @Component( selector: "blah", template: """blah""", directives: const [routerDirectives]) class Blah ext ...

Tips for Fixing Error: "We received a visitor for node type TSSatisfiesExpression that is not recognized as a valid type."

There seems to be an issue with Babel unable to compile my Storybook code. I'm working on setting up a boilerplate with Storybook and Next.js I've searched for a solution to this problem but couldn't find one. Any help would be greatly app ...

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() ...

I'm looking to enhance my Angular app by implementing a submenu that features various tabs

Currently, I am following a tutorial available at this link to achieve my desired outcome. However, I am facing some challenges because my tabs are not located in the root component. In my scenario, I have a contract with certain properties that I want to ...

The recommended filename in Playwright within a Docker environment is incorrectly configured and automatically defaults to "download."

Trying to use Playwright to download a file and set the filename using download.suggestedFilename(). Code snippet: const downloadPromise = page.waitForEvent('download', {timeout:100000}) await page.keyboard.down('Shift') await p ...

Error TS5023 occurs when the integrated terminal in Visual Studio Code encounters an unfamiliar option 'w' while executing the tsc -w command

I am encountering an issue with the tsc -w command in the VS Code integrated terminal. However, I have successfully executed it from the NodeJs Command Prompt. `error TS5023: Unknown option 'w' Use the '--help' flag to view available o ...

An array that solely needs a single element to conform to a specific type

While I was pondering API design concepts, a thought crossed my mind. Is it feasible to define a type in this manner? type SpecialArray<Unique, Bland> = [...Bland[], Unique, ...Bland[]]; However, the error message "A rest element cannot follow anoth ...

Confirm that the input field in Angular 5 has a default value before proceeding with validation

My form contains an input field with a default value. I am looking to add validation to ensure that the field has exactly 5 characters. <td> <input type="text" maxlength="5" ngModel #number="ngModel" name="number" value="{{data.number}}" ...

Discover the correct way to locate the "_id" field, not the "id" field, within an array when using Javascript and the MEAN stack

I am working on an Angular application that connects to MongoDB. I have a data array named books, which stores information retrieved from the database. The structure of each entry in the array is as follows: {_id: "5b768f4519d48c34e466411f", name: "test", ...

Exploring the depths of complex objects with the inclusion of optional parameters

I've been working on a custom object mapping function, but I've encountered an issue. I'm trying to preserve optional parameters as well. export declare type DeepMap<Values, T> = { [K in keyof Values]: Values[K] extends an ...

What are the steps for integrating Socket.IO into NUXT 3?

I am in search of a solution to integrate Socket.IO with my Nuxt 3 application. My requirement is for the Nuxt app and the Socket.IO server to operate on the same port, and for the Socket.IO server to automatically initiate as soon as the Nuxt app is ready ...

Tips for creating a cookie for an alternate website upon launching a new browser tab

Hey there, I'm facing an issue that I could really use some help with. To give you some context, I'm working on a project using Angular and TypeScript. My goal is to implement single sign-on functionality for multiple websites within one applica ...