一尘不染

Angular将回调函数作为@Input传递给子组件,类似于AngularJS的方式

angularjs

AngularJS具有&参数,您可以在其中将回调传递给指令(例如AngularJS的回调方式。是否可以将回调作为@InputAngularComponent的传递(如下所示)?如果不是,最接近的东西是什么AngularJS呢?

@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>

阅读 857

收藏
2020-07-04

共1个答案

一尘不染

我认为这是一个糟糕的解决方案。如果要使用将函数传递给组件@Input(),则需要@Output()装饰器。

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>
2020-07-04