Angular 2 Sibling Component Communication

前端 未结 12 1491
深忆病人
深忆病人 2020-11-22 06:31

I have a ListComponent. When an item is clicked in ListComponent, the details of that item should be shown in DetailComponent. Both are on the screen at the same time, so

12条回答
  •  别那么骄傲
    2020-11-22 07:17

    A directive can make sense in certain situations to 'connect' components. In fact the things being connected don't even need to be full components, and sometimes it's more lightweight and actually simpler if they aren't.

    For example I've got a Youtube Player component (wrapping Youtube API) and I wanted some controller buttons for it. The only reason the buttons aren't part of my main component is that they're located elsewhere in the DOM.

    In this case it's really just an 'extension' component that will only ever be of use with the 'parent' component. I say 'parent', but in the DOM it is a sibling - so call it what you will.

    Like I said it doesn't even need to be a full component, in my case it's just a

    The directive hooks everything up for me, and I don't have to declare the (click) event in the HTML.

    So the directive can nicely connect to the video player without having to involve ProductPage as a mediator.

    This is the first time I've actually done this, so not yet sure how scalable it might be for much more complex situations. For this though I'm happy and it leaves my HTML simple and responsibilities of everything distinct.

提交回复
热议问题