【问题标题】:Calling method on Template variables giving "undefined" exception调用模板变量的方法给出“未定义”异常
【发布时间】:2017-02-19 19:08:21
【问题描述】:

我有一个包含两个子组件的父组件。

AppComponent
     NotificationsComponent
     MoveCopyComponent

我想将 MoveCopyComponent 的值发送到 NotificationComponent。每当我发出时,我都会在 NotificationComponent 中得到一个未定义的属性,如屏幕截图所示

<notifications #notificationsMenu role="menuitem" dropdown-item 
       [caller]="'menu'" 
       (acceptShareFromMenuEvent)="shareAcceptModal.PinItem($event)"                                                                         
       (contentShareAccepted)="shareAcceptModal.hide()">
</notifications>

下面我们声明了一个组件,它会弹出一个模式来放置内容。

<movecopy-item #shareAcceptModal 
    (shareAcceptedandPlaced) = "notificationItem.contentAccepted($event)">

</movecopy-item>

模态(movecopy 组件)shareAcceptedandPlaced 事件中的按钮单击触发,我需要在通知组件中执行 contentAccepted(..) 方法,如下所示。

shareAcceptedandPlaced(){
       this.shareAcceptedandPlaced.emit(this.sharedItemPinnedInfo);     
}

这里发生的是,通知组件包含传入组件的集合,而 move-CopyItem 只是放置传入组件的选择组件。

当#shareAcceptModal 为“notificationItem 的” contentAccepted() 方法引发“(shareAcceptandPlaced)”事件时,我收到以下异常: “无法在未定义时调用 contentAccepted。如上图所示”

我在这里做错了什么?

【问题讨论】:

  • 完善您的帖子一次以提供清晰的信息。我读了你的帖子,它没有传达确切的信息。我对您的问题有所了解,并且遇到了这种情况。但需要更多信息。您可以在 teamviewer 中使用吗?
  • 感谢 Aravind,我添加了更多细节。我不在电视上,但在 Skype 上可用。

标签: angular angular2-components angular2-output


【解决方案1】:

错误

  1. 不能像这样调用子组件方法

    (shareAcceptedandPlaced) = "notificationItem.contentAccepted($event)"
    
  2. 您在事件shareAcceptedandPlaced()

  3. 中发出了一个不是通知子级的 Output() 变量

解决方案

  1. 因为你有 AppComponent 作为父级,你可以使用 @ViewChild() 对于子组件并访问属性和方法 你的两个子组件作为

    @ViewChild(movecopyComponent) mcopyComp: movecopyComponent;
    @ViewChild(NotificationsComponent) notificationMenu: NotificationsComponent;
    
  2. 如下修改&lt;movecopy&gt;中的方法调用

    <movecopy-item #shareAcceptModal (shareAcceptedandPlaced)="myContentChanged()">
    </movecopy-item>
    
  3. 你可以让你的 myContentChanged() 方法来处理它

    myContentChanged() {
           this.mcopyComp.properties....
           let temp: {...};        
           this.notificationMenu.contentAccepted(temp);
    }
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-07
    • 2017-09-25
    • 1970-01-01
    • 2012-11-10
    • 1970-01-01
    相关资源
    最近更新 更多