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.