Pennywise83
Pennywise83

Reputation: 1784

Reference dynamically generated id in Angular2 template

I'm using ngSemantic and I don't know how I can reference a dynamically generated ID.

I have several panels with a sidebar. To open the sidebar I need to declare

 (click)="sidebarId.show()"

I set the id of the sidebar in this way:

<sm-sidebar id="{{panelId}}-sidebar"></sm-sidebar>

I would need to call something like

(click)="{{panelId}}-sidebar.show()"

but this doesn't work since I receive this error:

Got interpolation ({{}}) where expression was expected at column 0 in [{{panelId}}-sidebar.show()] in PanelComponent@13:31

Upvotes: 2

Views: 887

Answers (4)

Zealitude
Zealitude

Reputation: 196

I haven't use ngSemantic. But id is not a instance, you can't use id to call any method Instead, you should use # to obtain the component instance, thus you can call the instance.method

    <h4 class="ui header">Demo</h4>
<sm-button class="positive icon" icon="sidebar" (click)="invertedSidebar.show({transition: 'overlay'})">
Lunch left sidebar</sm-button> 
<sm-sidebar class="left vertical inverted sidebar labeled icon menu" #invertedSidebar>        
    <a class="item">
        <i class="home icon"></i>
        Home
    </a>
    <a class="item">
        <i class="block layout icon"></i>
        Topics
    </a>
    <a class="item">
        <i class="smile icon"></i>
        Friends
    </a>
</sm-sidebar>

https://github.com/vladotesanovic/ngSemantic/blob/456c4198860d2d3ce49e975753bd79fef6881fca/demo/app/components/elements/sidebar.ts

For more complex case, you can pass the id to a custom function to obtain corresponding component instance by using @ViewChildren decorator https://angular.io/docs/ts/latest/api/core/index/ViewChildren-decorator.html

Upvotes: 1

birwin
birwin

Reputation: 2684

How about using eval() to evaluate the expression...

(click)="show(panelId)"


function show(panelId) {
    eval(panelId + '-sidebar.show()');
}

Upvotes: 0

dfsq
dfsq

Reputation: 193261

If you want to create dynamic names then you would use bracket notation:

(click)="this[panelId + '-sidebar'].show()"

Upvotes: 0

birwin
birwin

Reputation: 2684

If your component is within an *ngFor loop, you could use the index as the unique id. Otherwise, you could initialize a date object when the component is instantiated and use the timestamp as the unique ID as each date object.

Upvotes: 0

Related Questions