【问题标题】:Cannot import child component to parent component [duplicate]无法将子组件导入父组件[重复]
【发布时间】:2018-11-17 06:25:14
【问题描述】:

我正在使用 Angular 5。 我想从父组件调用子组件方法。为此,我添加 从'./myChild/myChild.component'导入{myChildComponent}; //错误:找不到模块./myChild/myChild.component

如何在 app.component.ts 以外的任何其他组件中导入子组件。(这里可以)

【问题讨论】:

  • 这里添加父子子组件代码
  • 你确定你有正确的 url 路径吗?
  • 导入路径可能错误
  • 只是一个说明,在其他组件中包含组件是不好的做法
  • 是的,当我尝试在 app.component.ts 中添加导入时它可以工作!

标签: angular viewchild


【解决方案1】:

您可以在 Angular 中使用 local variable 简单地从父组件调用子组件的函数。

例如

<hello name="{{ name }}" #childOne></hello>
<p (click)='childOne.callFromParent()'>
  Start editing to see some magic happen :)
</p>

这里hello 是子组件。

Working Example

第二种方式

<hello name="{{ name }}" #childOne></hello>
<button (click)='callChildFunction()'>hello</button>

@ViewChild('childOne') childOne: any;

callChildFunction() {
    this.childOne.callFromParent();
  }

【讨论】:

  • 不错!但我不确定它在我的场景中将如何工作。我有两个组件,一个是带有 2 个按钮的主组件,一个是用于地图视图的组件。当我单击 master 中的一个按钮时,我需要传递地图的标记类型。基于此,我可以在地图上绘制自定义标记。我尝试将它作为参数传递,但似乎在子组件或地图视图组件上未收到该值。这就是为什么我尝试从主组件调用 map-view 方法(更改地图标记)。
  • 五月@input/@output为你招数
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-05
  • 1970-01-01
  • 2021-05-16
  • 2020-09-23
  • 2021-07-04
  • 2019-10-19
  • 2021-02-22
相关资源
最近更新 更多