javascript - Angular - 如何将路由功能传递给子组件
问题描述
我尝试使用@Input() 将函数传递给子组件,但它返回错误“navigateSomeWhere() 不是函数”
父组件
navigateSomeWhere() {
this.router.navigate(['somewhere/']);
}
子组件
@Input() parentFunction : Function;
// Html
<button (click)="parentFunction()">Navigate</button>
解决方案
你有两个选择。
- 通过参数发送路线,您将在其中进行导航。
.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>
---------
- 创建一个 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>
---------
推荐阅读
- sql-server - 基于 SQL Server 查询重启 Windows 服务
- reactjs - 单元测试在 React Native 的条件渲染中失败
- accessibility - WCAG 2.0通用闪光灯定义中的“最大相对亮度”指的是什么?
- sql-server - Processmaker SQL Server 连接被拒绝
- reactjs - 无法在 React 中使用本地存储中的令牌
- javascript - 需要帮助验证 JavaScript 中的 PASETO 令牌的有效性。目前有依赖于有效载荷的不稳定行为
- c++ - 在 C++ 中通过迭代器将向量写入二进制文件的正确方法
- python - 所有值都进入 Django 表中的一列。怎么分开?
- laravel - 如何在 Laravel 中一次延迟加载所有集合的关系
- python - 通过将两列与不同 DataFrame 中的两个相似列进行比较,向 Pandas DataFrame 添加新列