Gaurav Shinh
Gaurav Shinh

Reputation: 21

How to reuse a custom Angular2 component multiple time on a page?

I have a simple Angular2 component called employee which populates and returns a HTML template based on the value of its attribute. E.g.

If I use, in my index.html - it will call my employeeComponent which will fetch data based on the attribute id( in this case "123") from database and populate html template. Let say for simplistic reason, it populates name for that employee and return something like

{{employee_name}}

.

This works fine first time, I call component and on subsequent calls it does not display any error nor does it render for

<employee id="123"></employee>
<employee id="121"></employee>
<employee id="122"></employee>

I want flexibility where I don't want to restrict number of tags. Since this is a 'view component' I dont want it be restricted inside main/app component. I want pure view reusability.

employee.component.ts

import {Component,  ElementRef}  from 'angular2/core';


@Component({
    selector: 'employee',   
    template: '{{id}}'
})

export class EmployeeComponent {
     id: number;
     name : string;

    constructor(elm: ElementRef){
         this.id = elm.nativeElement.getAttribute('id');
         console.log(elm.nativeElement);
    }

}

index.html

 <employee id="123"></employee>
  <employee id="121"></employee>
  <employee id="122"></employee>

main.ts

import {bootstrap}    from 'angular2/platform/browser';
import {AppComponent} from './app.component';
import {EmployeeComponent} from './employee.component';

bootstrap(AppComponent);
bootstrap(EmployeeComponent);

Any help appreciated to resolve this issue?

Upvotes: 2

Views: 3990

Answers (1)

Oliver Cooke
Oliver Cooke

Reputation: 1059

It looks like you might be getting mixed up, you should bootstrap your AppComponent and use the EmployeeComponent within the AppComponent template, this is how you will have to do it if you want to use angular 2 components. So your index body ends up having something like this.

index.html

<body>
   <my-app>Loading...</my-app>
</body>

If this structure is set up the control id's can be defined within app.component.ts and using input can be inserted into the component using ngFor. Then there will be different EmployeeComponents containing each of your id's, which you can set up a service to pull the relevant information from your database from within employee.

app.component.ts

export class EmployeeComponent {
    employeeIds: number[] = [123,124,125]
}

app.component.html

<employee *ngFor="let employeeId of employeeIds" [employeeId]="employeeId"><employee>

employee.component.ts

import {Component,  ElementRef, Input}  from 'angular2/core';

@Component({
    selector: 'employee',   
    template: '{{id}}'
})

export class EmployeeComponent {
    @input() id: number;
}

I hope I understand and have answered your question in a way that helps.

Upvotes: 5

Related Questions