123
123

Reputation: 555

Angular 2: How can I use the same component on a page with different html element ids?

I have a component that uses bootstrap's panel to display some data.

I made the panel collapsible using the data-toggle attribute.

panel.component.html

<div class="panel panel-primary">
  <div class="panel-heading clickable" href="#panel" data-toggle="collapse">
    <h4 class="panel-title">{{title}}</h4>
  </div>
  <div id="panel" class="panel-collapse collapse in">
    <!-- Some data here -->
  </div>
</div>

Now I want to use this component twice on the same page

<app-panel [title]="title 1" [data]="data1"></app-panel>
<app-panel [title]="title 2" [data]="data2"></app-panel>

Pressing the header of the top panel, collapses the body of the top panel (as it should).

The problem is that when I press the header of the bottom panel, it collapses the body of the top panel.

After inspecting the elements in the browser I noticed that it's because they're using the same id's (id="panel").

I know that it can be fixed by using the ng2-bootstrap module for example, but I prefer to fix it without adding additional 3rd party modules to my project.

So how can I use the same component more than once on the same page without the id attributes interrupting each other?

Upvotes: 2

Views: 2134

Answers (1)

Octavio Garbarino
Octavio Garbarino

Reputation: 772

An alternative is to pass the id as a parameter like you have passed the title and data. You can use the same method to pass the id to use, and use a default id if none is specified.

In panel.component.ts you could have something like:

@Input()
id: String = "panel";

Upvotes: 1

Related Questions