13

I have personInvolved component. This component has personDetails component. There is a button in personInvolved component. Onclick of the button I need to append the personDetails on DOM. each time I click it should append the personDetails component. How can I achieve this.

5
  • Do you want to remove the component and create it again each time? Or do you want to keep adding an instance on every click? Commented Aug 30, 2016 at 6:20
  • I want to add that component template URL each time Commented Aug 30, 2016 at 6:46
  • 1
    Then the below answer by @JB Nizet is the approach you should take. Commented Aug 30, 2016 at 6:48
  • How can I remove or pop the array in personDetails component. PersonDetail is having a button called remove Commented Aug 30, 2016 at 9:00
  • You're going to have to use a service. Take a look at this doc angular.io/docs/ts/latest/cookbook/… Commented Aug 30, 2016 at 9:10

1 Answer 1

24

Use *ngFor:

    <button (click)="addPerson()">Add person</button>
    <person-details *ngFor="let person of persons" [person]="person"></person-details>

And in the component code:

    persons: Array<Person> = [];

    addPerson() {
        this.persons.push(new Person());
    } 
Sign up to request clarification or add additional context in comments.

6 Comments

Here personDetails is other component having templateURL. I need to append the personDetails on click of addperson button in personInvolved component. First time it will append one <person-details>. Next time it should append one more persondetails on click.. And so on
What is new Person() method here ?
How can I remove or pop the array in personDetails component. PersonDetail is having a button called remove.
The person-details component should not be the one removing itself from its parent component's model. Either put the delete button out of the person-details component, or have it emit an event (using an EventEmitter), and listen to this event in the parent component to know that delete has been clicked and that the component should thus be removed from the array.
I have used eventEmitter, but how can I manage the index for which one to delete. I can able to pop the array but couldnot find which one has been clicked..Can you please help me
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.