ezzabuzaid / react-context-in-angular

1 stars 0 forks source link

Example #15

Open ezzabuzaid opened 3 years ago

ezzabuzaid commented 3 years ago

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

@Component({
    selector: 'app-chat-message',
    template: `
    <consumer name="ChatContext">
        <ng-template let-value>
            <h4>{{value.message}}</h4>
        </ng-template>
    </consumer>
    `
})
export class ChatMessageComponent { }

Chat Avatar Component Uses consumer to obtain the avatar. notice the changeDetection is changed to OnPush.

@Component({
    selector: 'app-chat-avatar',
    changeDetection: ChangeDetectionStrategy.OnPush,
    template: `
    <consumer name="ChatContext">
        <ng-template let-value>
            <img width="50" [src]="value.avatar">
        </ng-template>
    </consumer>
    `
})
export class ColorAvatarComponent { }

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

@Component({
    selector: 'app-chat-container',
    template: `
    <div style="display: flex;">
        <app-chat-avatar></app-chat-avatar>
        <app-chat-message></app-chat-message> 
        <provider name="ChatContext" [value]="{name:'Nested Provider Value'}">
            <app-chat-message></app-chat-message>
        </provider>
    </div>
    `
})
export class ChatContainerComponent { }

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.

@Component({
  selector: 'app-root',
  template: `
  <context name="ChatContext">
    <provider [value]="chatItem" name="ChatContext">
      <app-chat-container></app-chat-container>
    </provider>
  </context>
  <button (click)="updateChatItem()">Change Chat Item</button>
  `
})
export class AppComponent {
  chatItem = {
    message: 'Initial name',
    avatar: 'https://icon-library.com/images/avatar-icon-images/avatar-icon-images-4.jpg',
  }

  updateChatItem() {
    const randomInt = Math.round(Math.random() * 10);
    this.chatItem = {
      message: `Random ${ randomInt }`,
      avatar: `https://icon-library.com/images/avatar-icon-images/avatar-icon-images-${ randomInt }.jpg`,
    }
  }

}