AngularJS有&参数,你可以把一个回调传递给一个指令(例如AngularJS的回调方式)。是否可以将回调函数作为@Input传递给Angular组件(如下所示)?如果不是,那最接近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>
在某些情况下,您可能需要由父组件执行业务逻辑。在下面的例子中,我们有一个子组件,它根据父组件提供的逻辑来呈现表行:
@Component({
...
template: '<table-component [getRowColor]="getColor"></table-component>',
directives: [TableComponent]
})
export class ParentComponent {
// Pay attention on the way this function is declared. Using fat arrow (=>) declaration
// we can 'fixate' the context of `getColor` function
// so that it is bound to ParentComponent as if .bind(this) was used.
getColor = (row: Row) => {
return this.fancyColorService.getUserFavoriteColor(row);
}
}
@Component({...})
export class TableComponent{
// This will be bound to the ParentComponent.getColor.
// I found this way of declaration a bit safer and convenient than just raw Function declaration
@Input('getRowColor') getRowColor: (row: Row) => Color;
renderRow(){
....
// Notice that `getRowColor` function holds parent's context because of a fat arrow function used in the parent
const color = this.getRowColor(row);
renderRow(row, color);
}
}
所以,我想在这里演示两件事:
胖箭头(=>)代替.bind(this)来保存正确的上下文;
子组件中回调函数的类型安全声明。
对于我来说,除了.bind(this)之外,我还必须在要执行的方法名称后面加上一对括号。
在父组件中:
在.ts文件中:
this.pillTabs = [
{ tabName: 'Subscribers', tabMethod: this.showSubscribers.bind(this) },
{ tabName: 'Exemplars', tabMethod: this.showExemplars.bind(this) }
];
在.html文件中:
<pill-tabs [pillTabs]="pillTabs"></pill-tabs>
在Child组件中:
在.ts文件中:
@Input() pillTabs: PillTab[];
在.html文件中:
<div *ngFor="let pillTab of pillTabs; let i = index">
<input type="radio" id="{{'radio-' + i}}" name="tabs" [checked]="pillTab.checked"
(click)="pillTab.tabMethod()" />
<label class="tab" for="{{'radio-' + i}}">{{pillTab.tabName}}</label>
</div>
当我没有对括号后面的方法时,代码是不工作的:
(click)="pillTab.tabMethod"
然后当我在这里加上一对括号,代码就开始工作了。
(click)="pillTab.tabMethod()"
我希望有人觉得它有帮助。