Angular 5 - onclick event append component into div

23,787

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>
Share:
23,787
Admin
Author by

Admin

Updated on November 28, 2020

Comments

  • Admin
    Admin over 3 years

    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?

  • Admin
    Admin over 6 years
    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
  • Eliseo
    Eliseo over 6 years
  • Admin
    Admin over 6 years
    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 } }