首页 > 解决方案 > Angular - 如何将路由功能传递给子组件

问题描述

我尝试使用@Input() 将函数传递给子组件,但它返回错误“navigateSomeWhere() 不是函数”

父组件

navigateSomeWhere() {
  this.router.navigate(['somewhere/']);
}

子组件

@Input() parentFunction : Function;

// Html
<button (click)="parentFunction()">Navigate</button>

标签: javascriptangular

解决方案


你有两个选择。

  1. 通过参数发送路线,您将在其中进行导航。
.html

<myComponent myRoute="/login"></myComponent>
<myComponent myRoute="/principal"></myComponent>
<myComponent myRoute="/form"></myComponent>

---------

myComponent.ts

@Input myRoute: string;

public goToRoute(): void {
   this.router.navigate([this.myRoute]);
}


---------

myComponent.html

<button (click)="goToRoute()">Navigate</button>

---------
  1. 创建一个 eventEmitter 来执行您通过参数传递的函数。
.ts

public myFunction(): void {
   this.router.navigate([this.myRoute]);
}

---------

.html

<myComponentChild [myFunction]="myFunction()"></myComponentChild>

---------

myComponent.ts

@Output myFunction = new EventEmitter();

public goToRoute(): void {
   this.myFunction.emit();
}

---------

myComponent.html

<button (click)="goToRoute()">Navigate</button>

---------

推荐阅读