Angular 2+/4/5/6/7: Smart, dumb and deeply nested component communication

后端 未结 3 1822
执笔经年
执笔经年 2021-01-31 03:40

NOTE: for simplicity consider the component depths as:

- Smart (grand)parent level 0
  - dumb child level 1
   ....
    - dumb grandchild level 2
      ....)
         


        
3条回答
  •  渐次进展
    2021-01-31 04:38

    Why is #1 an anti-pattern? The grandparent component owns the data and passes it down to the dumb child components via @Input parameters. The dumb child components simply invoke callbacks when an event occurs (via @Output event emitters), causing the grandparent component to manipulate the data. Seems clean to me.

    Edit: I see your point about repeatedly passing values like a submit handler through many intermediate layers. Maybe a nested structure which represents your component tree could be created in the parent component. Then each component can be passed the properties it needs, plus an object to pass down to the next component. Each component then only knows about the one below it:

    // Parent component builds this object (or gets a service to do it)
    
    viewModelForChildComponent: {
    
        property1NeededForChildComponent,
    
        property2NeededForChildComponent,
    
        viewModelForGrandChildComponent: {
            property1NeededForGrandChildComponent,
    
            property2NeededForGrandChildComponent,
    
            viewModelForGrandGrandChildComponent: {
                property1NeededForGrandGrandChildComponent,
    
                submitHandlerNeededForGrandGrandChildComponent
            }
        }
    }
    

提交回复
热议问题