Reputation: 5522
I'm trying to create a component several times on a button click. The button is in the parent component and when the click "Add more" it will create the child component as many times as they click "Add more". By default there's only one child component showing then when we click on the button the same child component will be added after the existing one.
how to create existing child component multiple times on button click?
Should I use component Factory or just a plain forLoop?
HTML -Child component
<input type="text />
HTML -Parent component
<child-component #childCom></child-component>
<button (click)="addMore()">Add more</button>
TS
@ViewChild('childCom') childCom: ElementRef;
addMore(){
console.log("child component");
}
Upvotes: 0
Views: 3329
Reputation: 845
Use ComponentFactoryResolver for this
Add ng-template
into your HTML page where you want to generate dynamic component
<child-component #childCom></child-component>
<ng-template #container></ng-template>
then in your component.ts
@ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;
input = InputComponent;
constructor(private componentFactoryResolver: ComponentFactoryResolver) {
}
InputComponent
is child-component according to your code
add() {
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(this.input);
const component = this.container.createComponent(componentFactory);
}
and don't forget to bootstrap your child-component in NgModule
bootstrap: [AppComponent], entryComponents: [InputComponent]
Upvotes: 1
Reputation: 19764
Use a for loop for display a component multiple times.
Each time you want to add a new item, we'll add another item into the array (for example the array could be 0
, 1
, 2
or you could keep some state there -- this depends on your app).
public items = []
public add () {
this.items = [...this.items, this.items.length]
}
We call the add
method from the template when you click a button.
<button (click)="add()">Add</button>
And we iterate over the array and create the component multiple times.
<child-component *ngFor="let item of items"></child-component>
When the user clicks the button, method add
is called. This makes the length of the array longer by one. ngFor
notices this and renders another item.
Upvotes: 2