Allow the user to control the view of the toggle component. Break the toggle component to multiple composable components of the can is rearranged by the app developer.
Compound component mainly for rendering flexibility. It hides the implements detial from users, but users can freely re-order the child component order or add new component in to it.
In this post we is looking into how to apply the "@ConetentChild" to does compound components.
This is a recommended-a-just for learning!
So a highlevel compound component looks like:
<Toggle(toggle)= "Ontoggle ($event)"> <Toggle-button></Toggle-button> <toggle-on>On</toggle-on> <Toggle-off>Off</Toggle-off></Toggle>
For the parent component ' toggle ' component, the job for it's hide implement details from the consumers. IT handles the internal state. Which means ' toggle ' component needs to access the state of it children components.
< Toggle-button ></ Toggle-button > < toggle-on > On</toggle-on><Toggle-off>off </toggle-off>
The can accomplish it is using ' @ContentChild ':
@ContentChild (toggleoncomponent) toggleon:toggleoncomponent; @ContentChild (toggleoffcomponent) Toggleoff: Toggleoffcomponent, @ContentChild (togglebuttoncomponent) togglebutton:togglebuttoncomponent;
Listen for child component ' s Ouput event:
Toggle-button component has the Output event call ' toggle ':
@Component ({selector:'Toggle-button', Template:'<switch [on]= "on" (click) = "OnClick ()" ></switch>',}) Exportclasstogglebuttoncomponent {@Input () On:boolean; @Output () Toggle:eventemitter<boolean> =NewEventemitter (); OnClick () { This. on =! This. On; This. Toggle.emit ( This. On); }}
Then we can listen the Output event in ' ngaftercontentinit () ' Lifecycle hooks.
Ngaftercontentinit () { this. ToggleButton.toggle.subscribe (on = = {This . On = on ; This . Toggle.emit (on); This . Update (); });
Also ' Toggle ' component'll take care to update children the state:
Update () { This]on; This This . On; This This . On; }
[Angular] Write Compound components with Angular ' s contentchild