tzimom
tzimom

Reputation: 355

How can I display an angular component that is initialized from code?

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.

Upvotes: 0

Views: 994

Answers (2)

robert
robert

Reputation: 6152

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

Upvotes: 1

Bruno Cunha
Bruno Cunha

Reputation: 282

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);
}

Upvotes: 1

Related Questions