Inject parent component of the same type as child component

前端 未结 3 1925
走了就别回头了
走了就别回头了 2020-12-14 23:22

In Angular 2, a child component can get its parent component injected through a constructor parameter. Example:

@Component({...})
export class ParentComponen         


        
3条回答
  •  不知归路
    2020-12-14 23:32

    This post has been solved thanks to Günther. However, I would like to follow up based on the architectural feedback I got.

    First and foremost: I completely agree that the TreeNodeComponent use case example is an anti pattern. A data driven component like a tree this should be controlled by data binding. My apologies for this anti pattern.

    However, my actual use case (which is more complex to explain) is that I want to develop an advanced dropdown menu. Requirements:

    • The dropdown should have arbitrary number of levels (menu, submenu, subsubmenu etc)
    • The dropdown is defined at design time - its content is not based on dynamic data.
    • It should be possible to attach event handlers (_)= to each dropdown item.
    • It should be possible to insert custom control components into the dropdown.

    A usage example:

    
      
      
      
        
        
          
        
        
          
          
          
        
        
    

    My consideration is that this would be hard to implement using data binding. It's much practical to be able to bind event handlers and include custom components this way.

    But I might be wrong! Any opinions about this are highly welcome!

提交回复
热议问题