patterntypescriptangularCritical
Angular pass callback function to child component as @Input similar to AngularJS way
Viewed 0 times
angularinputangularjsfunctioncomponentsimilarchildwaycallbackpass
Problem
AngularJS has the & parameters where you could pass a callback to a directive (e.g AngularJS way of callbacks. Is it possible to pass a callback as an
@Input for an Angular Component (something like below)? If not what would be the closest thing to what AngularJS does?@Component({
selector: 'suggestion-menu',
providers: [SuggestService],
template: `
`,
changeDetection: ChangeDetectionStrategy.Default
})
export class SuggestionMenuComponent {
@Input() callback: Function;
suggestionWasClicked(clickedEntry: SomeModel): void {
this.callback(clickedEntry, this.query);
}
}
Solution
I think that is a bad solution. If you want to pass a Function into component with
@Input(), @Output() decorator is what you are looking for.export class SuggestionMenuComponent {
@Output() onSuggest: EventEmitter = new EventEmitter();
suggestionWasClicked(clickedEntry: SomeModel): void {
this.onSuggest.emit([clickedEntry, this.query]);
}
}
Code Snippets
export class SuggestionMenuComponent {
@Output() onSuggest: EventEmitter<any> = new EventEmitter();
suggestionWasClicked(clickedEntry: SomeModel): void {
this.onSuggest.emit([clickedEntry, this.query]);
}
}
<suggestion-menu (onSuggest)="insertSuggestion($event[0],$event[1])">
</suggestion-menu>Context
Stack Overflow Q#35328652, score: 416
Revisions (0)
No revisions yet.