Add component to dom on click of button in angular

2020-06-13 20:06发布

问题:

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.

回答1:

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());
    } 


标签: angular