2

I want a generic list component which a ''fetch'' method will be injected to. this didn't work through '@input', so i tried output, but it also doens't work for some reason. how can I do this and why doesn't this work?

ParentComponent

HTML

<app-list (requestFetch)="fetch($event)"></app-list>  

TypeScript

fetch(stuff) {        
    console.log('fetching'); //this doesn't get called...
    this.dataservice.get().subscribe(data=>{
    console.log('fetched');
    stuff(data);
    });
 }    

Listcomponent

@Output()
requestedFetch:EventEmitter<Function> = new EventEmitter<Function>  );                

constructor()
{            
   console.log('requesting data');
   this.requestedFetch.emit(this.setData);
}

setData(data) {
   console.log('found data');
  //do stuff with the fetched Data
}

EDIT Changed onRequestedFetch to requestedFetch and added comments. still doesn't work :(

2 Answers2

1

You having requestedFetch as your output variable and your using onRequestFetch in your HTML.

Modify it as

<app-list (requestedFetch)="fetch($event)"></app-list>  
Aravind
  • 40,391
  • 16
  • 91
  • 110
1

Execute

this.requestedFetch.emit(this.setData);

in OnInit instead of the constructor:

ngOnInit() {
  this.requestedFetch.emit(this.setData);
}

Check the Difference between Constructor and ngOnInit

Here when we call it in OnInit, we are sure of the Angular is done creating the component and we have everything available that we need.

DEMO

AT82
  • 71,416
  • 24
  • 140
  • 167
  • Great, glad to hear it worked! Since it solved your issue, you can consider marking the answer as accepted by clicking th grey tick under the voting of this answer, which marks the question as solved :) But furthermore have a great day and happy coding! :) :) – AT82 Jul 04 '17 at 12:45