Floriane Floriane - 1 year ago 93
TypeScript Question

Use boolean variable in several components

how can I use a boolean variable initialized in a component in other components ?
Let me explain :
I have a boolean variable 'flash' that I initialize in my component 'chat-threads'.

<div class="flash-signal">
Signal visuel :
<input type="radio" name="flashsignal" id="flashsignal1" checked="checked" (click)="flashSignal()">
<label for="flashsignal1">Oui</label>
<input type="radio" name="flashsignal" id="flashsignal2" (click)="notFlashSignal()">
<label for="flashsignal2">Non</label>
</div>


Other code :

export class ChatThreadsComponent implements OnInit {

flash = true;

constructor(public threadsService: ThreadsService,
public messagesService: MessagesService,
public boxService: BoxService) {
this.threads = threadsService.orderedThreads;
}

ngOnInit(): void {
this.flash = true;
}

notFlashSignal(): void {
this.flash = false;
}

flashSignal(): void {
this.flash = true;
}
}


I would like to be able to read the value of this variable in another component 'chat-window' in order to be able to display a visual signal or not.

<div [ngClass]="{'notification-message-unread' : !box.thread.lastMessage.isRead && flash}">


Do I have to implement this variable in my component?

EDIT :

export class Box {
id: string;
thread: Thread;
discussion: Observable<Message[]>;
flash: boolean;

constructor(id?: string,
thread?: Thread,
messages?: Observable<Message[]>,
flash?: boolean
) {
this.id = id || uuid();
this.thread = thread || null;
this.discussion = messages;
this.flash = flash || true;
}


}

Component :

<div [ngClass]="{'notification-message-unread' : !box.thread.lastMessage.isRead && !box.flash}">

Answer Source

When two components are not having any parent child relationship, the best way is a shared service injected into the constructors of A and B.

component A:

constructor(private sharingService: SharingService) { }

component B:

constructor(private sharingService: SharingService) { }

Service:

import { Injectable, } from '@angular/core';

@Injectable()

flash: boolean = true;

constructor() {}

You can use it in components using this.sharingService.flash. For complete reference see this.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download