2
votes

Main Component :

Html

<event-thumbnail *ngFor='let event1 of events' #thumbnail  [event2]="event1" (eventClick)='handleEventClicked($event)'>Hello</event-thumbnail>
<button class='btn btn-primary' (click)="thumbnail.alertFoo()">alert id</button>
<button class='btn btn-primary' (click)='thumbnail.handleClickMe()'>click me!</button>

Event-Thumbnail Componenent

  alertFoo(){
    alert("id called");
  }

  handleClickMe(){
    this.eventClick.emit('foo');
    alert('click');
  }

In the above code I am unable to use button using thumbnail -> template variable when using *ngFor ie. no call is made to alertFoo and handleClickMe() via thumbnail. I also tried to wrap it inside div and still it doesnt work. It only works when I am enclosing the whole code inside a div with *ngFor i.e. also buttons which displays undesirable multiple buttons. I want to understand how ngFor works is there some work around for the above where i want events to be repeated but the buttons to be displayed only once.

1
What are these methods really? What's the prefix thumbnail referring to? Not really sure, that's why I am asking. You are providing very little code to try and solve this issue. Best would be if you could reproduce the issue in a plunker... :) - AT82
@AJT_82 i think above code is self explainatory ..... if you know angular2 #thumbnail is template variable it is referring to th event-thumbnail template I am trying to call alertzfoo() and handleClickMe() method present in event-thumbnail component via the template variable thumbnail which is not working in the above code snap when i encapsulate everything inside a div I see multiple buttons populated in my page as it also becomes the part of ngFor. - Gopherine
No the code was NOT self-explanatory, now it's more clear though, since you provided WHERE these methods are, i.e in the event-thumbnail component. - AT82
@AJT_82 ok I think now it is now much more clear .... ? - Gopherine
Yup, so I whipped up an answer for you :) - AT82

1 Answers

1
votes

Use ViewChild for this purpose. Here's an example. Since not knowing exactly how your components are named, I'm using dummy name here. So parent:

Template:

<button (click)="alertFooInChild()">Click</button>

TS:

@ViewChild(AppChild) appChild: AppChild;

alertFooInChild() {
  // call the method in the child
  this.appChild.alertFoo();
}

Here's a demo plunker :)