Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add component to dom on click of button in angular2

Tags:

angular

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.

like image 618
raj m Avatar asked Aug 30 '16 06:08

raj m


People also ask

How to add click event to a button in angular?

Let’s add changes in the Angular component. In Html template component- app.component.html: Added click event to a button with event binding syntax i.e bracket () symbol the event name is the name of the function placed inside the bracket. This function is called when the button is clicked.

How to display button code in angular?

In Angular application, displaying button code is placed in HTML template page i.e view. The trigger event is placed in the typescript component class. So user event information will be passed from view to component class.

What is the use of componentfactory in angular?

For each component listed here, Angular will create a ComponentFactory and store it in the ComponentFactoryResolver. The entryComponents will create a factory so that when the ComponentFactoryResolver is called we are able to create an instance of the component and add it to the DOM.

How to manipulate Dom in angular?

There are many ways to manipulate the DOM in Angular. Let's use them instead of straight forward JavaScript approaches. Usually, there are two concepts in DOM Manipulations. Modifying DOM Elements. Modifying DOM Structure.


1 Answers

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());
    } 
like image 89
JB Nizet Avatar answered Oct 25 '22 22:10

JB Nizet