0

I have the following setup:

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 goal is to be able to dynamically (for example using a button) generate new users via code like new UserComponent('NAME'); and add them to the users array in the users component.

My question is: How can I display a component that is initialized from code?

I tried something like this:

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

but that just outputted '[object Object]'.

Maybe I have a completely wrong approach but I thought this could be the easiest solution, if it works.

0

2 Answers 2

1

You need to keep track of data in the most part and Angular will handle the view for you.

Take a look at this demo

Sign up to request clarification or add additional context in comments.

Comments

1

How to show object property in template?

Your use is an object, so you have to indicate in HTML what property of this object you want to show:

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

How to generate more items and display in list?

Angular, automatically, bind your TS variables with your template. So, just update your users list with new users that Angular will update view. For 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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.