Chat Container Component
Group the other components and perhaps for styling and aligning. it uses the provider declared in AppComponent for the first chat message and a new provider for the second chat message
App Component
Declare a context with the name ChatContext with no default value and a provider with initial value chatItem which will be shared to ChatMessageComponent and ChatAvatarComponent.
Clicking on the Change Chat Item button will update the chatItem reference hence updating the consumers to get the new value.
To put the implementation in action, I'll use chat components to illustrate the usage of the context.
Follow the demo to see the result.
Chat Message Component Uses consumer to obtain the message
Chat Avatar Component Uses consumer to obtain the avatar. notice the
changeDetection
is changed toOnPush
.Chat Container Component Group the other components and perhaps for styling and aligning. it uses the provider declared in
AppComponent
for the first chat message and a new provider for the second chat messageApp Component Declare a context with the name ChatContext with no default value and a provider with initial value
chatItem
which will be shared toChatMessageComponent
andChatAvatarComponent
.Clicking on the Change Chat Item button will update the
chatItem
reference hence updating the consumers to get the new value.