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>
Author by
Admin
Updated on November 28, 2020Comments
-
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 over 6 yearsWhat 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 over 6 yearsPerhapf some like blog.dmbcllc.com/dynamically-add-components-in-angular ?
-
Admin over 6 yearsSeems 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 } }