I have encountered an issue while passing a function
from the parent component to the child component's Input()
property.
The problem arises when the parent's function is called within the child component, causing the this
keyword to refer to the child component's context instead of the parent component's context.
Below is an example implementation in the parent component:
export class CustomerComponent implements OnInit {
next(continuationToken: string): Observable<CustomerSearchResult> {
console.log('invoked');
return this.customerService.searchCustomersPaged("andrew");
}
}
In the parent component's template (passing the 'next' function as 'nextDelegate' input parameter):
<app-datatable [hidden]="!customersByFirstNameHasResults" [nextDelegate]="next" [serverSidePaging]="true" id="customersByFirstName" [showDeleteButton]="false" [showEditButton]="true" [responseModelObservable]="customersByFirstName"
modelTypeName="customer" (editRow)="editCustomer($event)">
</app-datatable>
When attempting to invoke the method passed in within the child component, the context
is incorrect.
export class DatatableComponent implements AfterViewInit, OnDestroy, OnInit {
@Input() nextDelegate: (continuationToken: string) => Observable<CustomerSearchResult>;
private initializeDtOptions() {
// Storing current class reference in a variable to use it in jQuery
// Function because we can't
// Use arrow function as we might need both 'this' references
if (this.serverSidePaging) {
this.dtOptions = {
pagingType: 'simple',
serverSide: true,
processing: true,
pageLength: 10,
deferLoading: 100, //this.totalRecords
ajax: (p, callback) => {
// Called here
that.nextDelegate("").subscribe(x => {
callback({
})
});
}
};
} else {
this.dtOptions = {
pagingType: 'full_numbers',
columns: this.columnSettings
};
}
}
}