You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 18子组件触发父组件方法时依赖注入失效问题

Angular 18子组件触发父组件方法时依赖注入失效问题解决

问题原因

直接将父组件的actionInParent方法作为@Input传给子组件时,方法的this上下文会丢失。在子组件中调用该方法时,this不再指向ParentComponent实例,导致this.router为undefined,从而抛出Cannot read properties of undefined (reading 'navigateByUrl')错误。

解决方法

以下两种方式可有效保留方法的this上下文:

方法1:保留父组件方法的this指向

方式1.1:模板中用箭头函数包裹

修改父组件模板,通过箭头函数捕获父组件的this上下文:

<app-child [action]="() => actionInParent()" />

方式1.2:组件类中绑定this

将方法定义为箭头函数,或者在构造函数中绑定this:

export class ParentComponent {
  private router = inject(Router);

  // 箭头函数自动绑定父组件this
  actionInParent = () => {
    console.log("Action invoked");
    this.router.navigateByUrl('child');
  };
}

或者使用bind手动绑定:

export class ParentComponent {
  private router = inject(Router);

  actionInParent() {
    console.log("Action invoked");
    this.router.navigateByUrl('child');
  }

  constructor() {
    this.actionInParent = this.actionInParent.bind(this);
  }
}

方法2:使用@Output事件通信(Angular推荐方案)

改用@Output事件发射器实现父子组件通信,完全规避this上下文问题:

修改子组件(child.component.ts):

import { Component, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-child',
  standalone: true,
  imports: [],
  template: `
    <button type="button" (click)="action.emit()">Navigate using child</button>
  `,
  styles: ``
})
export class ChildComponent {
  @Output() action = new EventEmitter<void>();
}

修改父组件模板:

<app-child (action)="actionInParent()" />

验证效果

采用上述任意一种方法后,点击子组件按钮均可正常触发导航,不再出现依赖注入相关的错误。

内容的提问来源于stack exchange,提问作者perissf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 16:11:05