What is the best way to showcase an Angular component that has been initialized programmatically?

I currently have the following set up:

Users Component HTML:

<div class="users">
  <ul class="users__list">
    <li *ngFor="let user of users"></li>
  </ul>
</div>

Users Component TS:

import { Component, OnInit } from '@angular/core';
import { UserComponent } from '../user/user.component';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.scss'],
})
export class UsersComponent implements OnInit {
  users: UserComponent[] = [];

  ngOnInit(): void {
    this.users.push(new UserComponent('Test User'));
  }
}

User Component HTML:

{{ name }}

User Component TS:

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

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.scss'],
})
export class UserComponent {
  constructor(@Inject('name') public name: string) {}
}

My objective is to dynamically generate new users (for instance, using a button) by utilizing code like new UserComponent('NAME'); and then include them in the users array within the users component.

Thus, my query is: How can I exhibit a component that has been initialized via code?

I experimented with the following approach:

<div class="users">
  <ul class="users__list">
    <li *ngFor="let user of users">{{ user }}</li>
  </ul>
</div>

but unfortunately, it merely displayed '[object Object]'. Perhaps my method is completely misguided, but I believed it could be the simplest solution if it functioned as intended.

Answer №1

By managing data efficiently, Angular can take care of the presentation layer.

Check out this live demonstration

Answer №2

How can I display a specific property of an object in my template?

If you are working with an object, you need to specify which property of the object you want to display in your HTML:

<div class="users">
  <ul class="users__list">
    <li *ngFor="let user of users">{{ user.name }}</li>
  </ul>
</div>

Is it possible to dynamically add more items to a list in Angular?

Angular automatically binds your TypeScript variables to your template, so simply update your 'users' list with new entries and Angular will take care of updating the view. Here's an example:

/* User.ts */
export class User {
 name: string;

 constructor(name: string) {
  this.name=name;
 }
}

/* UsersComponent.ts */
addUser() {
 const newUser = new User("I'm a new user!");
 this.users.push(newUser);
}

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 arrays of objects sharing a common key yet varying in structure

Currently, I am facing a challenge while working on this problem using Typescript. It has been quite some time since I started working on it and I am hoping that the helpful community at StackOverflow could provide assistance :) The scenario involves two ...

Tips on clearing local storage when the browser is closed or a tab is closed in JavaScript, Angular, and React

Is there a way to automatically remove local storage or session storage data when closing the browser? Specifically, how can I delete the local storage details only when closing the final tab of a website with multiple tabs open? I've attempted variou ...

Obtaining data from a TypeScript decorator

export class UploadGreetingController { constructor( private greetingFacade: GreetingFacade, ) {} @UseInterceptors(FileInterceptor('file', { storage: diskStorage({ destination: (req: any, file, cb) => { if (process.env ...

What is the best way to transfer information from the window method to the data function in a Vue.js application?

Is there a way to transfer information from the window method to the data function in a vuejs component? Take a look at my window method: window.authenticate = function(pid, receiptKey) { console.log("Authentication"); console.log(this) localStorag ...

What could be causing my webpack bundler to generate several main.js files?

After realizing that tree shaking was not working correctly due to compiling TypeScript to 'commonjs', I switched it to 'ES2015' and now my build output appears like this: click here for the image. Can anyone explain what is happening ...

Will the async pipe activate onPush change detection in Angular?

I have searched various sources for the question above, but I am finding conflicting answers. For example, on Angular University's website, it is mentioned that change detection is triggered when the async pipe receives a new observable value. However ...

Adding two headers to a post request in Angular 2 - a step-by-step guide!

Is there a way to combine 2 headers in the following code snippet: appendHeaders(json: PortfolioVO) { var newJson = JSON.stringify(json); var allHeaders = new Headers(); allHeaders.append('Content-type' , 'application/jso ...

Troubleshooting login problems with MSAL and AD B2C

Despite dedicating a significant amount of time to learning and implementing MSAL, I am still facing challenges. Multiple issues have left me unsure of how to proceed or where I might be going wrong. Here is what I have accomplished so far: 1) Downloaded ...

Efficiently setting HttpParams like HttpHeaders in Angular: A streamlined approach

Having recently made the switch from using the old Http API to the new HttpClient API in Angular, I found myself needing to work with HttpHeaders and HttpParams. So far, everything is going smoothly. However, the examples I came across for declarations see ...

The usage of the import statement outside a module is not permitted in a serverless Node application

I am currently in the process of migrating a serverless AWS lambda microservices API to TypeScript. My goal is to retain the existing JavaScript files while incorporating more TypeScript files as we progress. However, I am encountering difficulties with co ...

Angular Firebase Email Verification sent to an alternate email address

I am facing a challenge with my website that only accepts emails from a specific domain, such as a university domain. Users who want to sign up using Facebook or Google need to verify their university email, but I am struggling to find a way to send the ve ...

The 'setComputed' property is not mandatory in the type definition, however, it is a necessary component in the 'EntityExample' type

I'm encountering an issue while trying to create a factory for updating an entity. The error I'm facing is related to the usage of afterload: Entity: import { Entity, PrimaryGeneratedColumn, Column, OneToMany, BaseEntity, AfterLoad, ...

Tips for sending icons as properties in React using TypeScript

Recently diving into typescript, I embarked on a straightforward project. Within this project lies a sidebar component that comprises multiple sidebarNavigationItem components. Each of these Sidebar items consists of an Icon and Title, showcased below. Si ...

Listen for incoming data from the client in the form of an ArrayBuffer

I have been utilizing the ws library within nodejs to develop a small cursor lobby where players can interact. I have managed to utilize the server to send ArrayBuffers with bit streams to the client and successfully decode them. However, I am encountering ...

Optimal techniques for Angular 2 and beyond

When creating a CRUD for an entity using a REST API, what is the recommended best practice for updating data? On the main screen where there is a list of elements and a new element is added through a modal, should the list be updated locally or by callin ...

Steps to properly specify the Express Error Type

When defining the variable err, I have opted to use any due to uncertainty about the correct type. I was anticipating an express.Error type, but none was found. What would be the appropriate way to assign a type to err? // Addressing Syntax Error in JSON ...

What techniques can I use to modify an object while it's being iterated through?

I've been attempting to manipulate the object while looping through it, but unfortunately, it's not working. How can I modify it so that the constant patient includes the property lastActivity inside the this.model array? My code looks like this ...

What steps can be taken to eliminate redundancy in this code and improve its efficiency?

Here I have two methods, create and update, that send data to an API. I am looking to enhance the createUser and updateUser methods as they are very similar. Additionally, if you have any suggestions on a better way to directly set the id property as null ...

Converting an array of objects to an array based on an interface

I'm currently facing an issue with assigning an array of objects to an interface-based array. Here is the current implementation in my item.ts interface: export interface IItem { id: number, text: string, members: any } In the item.component.ts ...

Navigating through the exported components of a module without explicit type declarations

So I'm in the process of developing a module with sub-modules for Angular. Here's the notation I'm using: module App.services { export class SomeService { } } When initializing all services, I use the following code snippet: function ...