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: '<child [myCallback]="theCallback"></child>',
  directives: [ChildComponent]
})
export class ParentComponent{
  public theCallback(){
    ...
  }
}

@Component({...})
export class ChildComponent{
  //This will be bound to the ParentComponent.theCallback
  @Input()
  public myCallback: Function; 
  ...
}

其他回答

传递带有参数的方法,在模板中使用.bind

@Component({
  ...
  template: '<child [action]="foo.bind(this, 'someArgument')"></child>',
  ...
})
export class ParentComponent {
  public foo(someParameter: string){
    ...
  }
}

@Component({...})
export class ChildComponent{

  @Input()
  public action: Function; 

  ...
}

使用可观察模式。你可以把可观察值(不是主题)放入输入参数,并从父组件管理它。你不需要回调函数。

参见示例:https://stackoverflow.com/a/49662611/4604351

对于我来说,除了.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()"

我希望有人觉得它有帮助。

我认为这是一个糟糕的解决方案。如果你想通过@Input()将Function传递给组件,@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>

目前的答案可以简化为……

@Component({
  ...
  template: '<child [myCallback]="theCallback"></child>',
  directives: [ChildComponent]
})
export class ParentComponent{
  public theCallback(){
    ...
  }
}

@Component({...})
export class ChildComponent{
  //This will be bound to the ParentComponent.theCallback
  @Input()
  public myCallback: Function; 
  ...
}