3

I am using Angular 5 and I have this:

// app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  appendToContainer() {
    // Do the stuff here
    // Append PanelComponent into div#container
  }

}

Now the app.component.html

// app.component.html
<button (click)="appendToContainer()"></button>
<div id="container"></div>

and finally I have a simple component

// panel.component.html
<div class="panelComponent">
  This is a panel Component html
</div>

What I want to do is that everytime the button on app.component.html is click I need a panel.component appended into app.component.html

How can I do this?

4
  • I have the feeling you take that problem from the wrong side. Shouldn't you iterate an array with a *ngFor? Commented Nov 27, 2017 at 14:07
  • you can use an object array that you can append to when calling appendToContainer and use *ngFor to create a panel for each item in the array Commented Nov 27, 2017 at 14:08
  • What I want to do it the create a new instance on the component and append it inside the div when the button is clicked Commented Nov 27, 2017 at 15:44
  • @pedromartinez did you find any solution? Commented Nov 14, 2019 at 9:23

1 Answer 1

1

You can use a *ngFor and a variable to achieve you want

//In your component
num:number=0

//You html like 
<button (click)="num++"></button>
//we create a array "on fly" and slice to get only a "num" items
<div *ngFor="let item in [0,1,2,3,4,5,6,7,8,9].slice(0,num)" class="panelComponent">
  This is a panel Component html
</div>
Sign up to request clarification or add additional context in comments.

3 Comments

What I want to do it the create a new instance on the component and append it inside the div when the button is clicked
Seems that the code there is not for angular 5. Here's my app.component.ts: import { Component } from '@angular/core'; import { ChildComponent } from './child/child.component'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { constructor() {} addCmp() { console.log('adding'); // Add an instance of ChildComponent } }