Angular将回调函数作为@Input传递给子组件,类似于AngularJS的方式 [英] Angular pass callback function to child component as @Input similar to AngularJS way
本文介绍了Angular将回调函数作为@Input传递给子组件,类似于AngularJS的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
AngularJS具有&您可以在其中将回调传递给指令的参数(例如 AngularJS回调方式.是否可以将回调作为@Input
传递给Angular组件(如下所示)?如果没有,那么最接近AngularJS的东西是什么?
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: `
<div (mousedown)="suggestionWasClicked(suggestion)">
</div>`,
changeDetection: ChangeDetectionStrategy.Default
})
export class SuggestionMenuComponent {
@Input() callback: Function;
suggestionWasClicked(clickedEntry: SomeModel): void {
this.callback(clickedEntry, this.query);
}
}
<suggestion-menu callback="insertSuggestion">
</suggestion-menu>
推荐答案
我认为这是一个糟糕的解决方案.如果要使用@Input()
将Function传递到组件中,则需要使用@Output()
装饰器.
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<any> = new EventEmitter();
suggestionWasClicked(clickedEntry: SomeModel): void {
this.onSuggest.emit([clickedEntry, this.query]);
}
}
<suggestion-menu (onSuggest)="insertSuggestion($event[0],$event[1])">
</suggestion-menu>
这篇关于Angular将回调函数作为@Input传递给子组件,类似于AngularJS的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文