Calling method on Template variables giving “undefined” exception

梦想的初衷 提交于 2019-12-11 04:25:08

问题


I have one parent containing two child components.

AppComponent
     NotificationsComponent
     MoveCopyComponent

I want to emit values of MoveCopyComponent to NotificationComponent. Whenever I emit i get a property undefined in the NotificationComponent as shown in the screenshot

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

And down below we have declared a component which pops a modal to place the content.

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

</movecopy-item>

A button click in the modal(movecopy component) shareAcceptedandPlaced event is triggered by which I need to execute contentAccepted(..) method in my notifications component as below.

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

What is happening here is that the notifications component contains the collection of the incoming components while the move-CopyItem is merely a selection component to place the incoming component.

When the #shareAcceptModal raises the "(shareAcceptandPlaced)" event for the "notificationItem's" contentAccepted() method, I get the following exception: "Cannot call contentAccepted on undefined. as in the above screenshot"

What am I doing wrong here?


回答1:


Mistakes

  1. You cannot call the child component method like

    (shareAcceptedandPlaced) = "notificationItem.contentAccepted($event)"
    
  2. You are emitting a Output() variable which is not a child of notifications in your event shareAcceptedandPlaced()

Solution

  1. Since you have AppComponent as a parent, you can use @ViewChild() for both the child components and access the properties and methods of your both child components as

    @ViewChild(movecopyComponent) mcopyComp: movecopyComponent;
    @ViewChild(NotificationsComponent) notificationMenu: NotificationsComponent;
    
  2. Modify your method call in the <movecopy> as below

    <movecopy-item #shareAcceptModal (shareAcceptedandPlaced)="myContentChanged()">
    </movecopy-item>
    
  3. You can have your myContentChanged() method to handle it as

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


来源:https://stackoverflow.com/questions/42324913/calling-method-on-template-variables-giving-undefined-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!