Problem:
The problem is that when you request a new component, which is not showing, you must communicate with the existing component through a service in my opinion.
Solution:
I leave you an example using Subject, to notify changes and / or send information between components effectively, since @Input () becomes tedious when they are widely separated.
Example:
Alert Service:
This service makes use of Subject, a type of Observable, which allows sending a message, using the method .next()
to all those who are subscribed to it.
Those who are subscribed to this element will receive the object that is put inside the .next()
method. In your case, it will be the new heat of the variable Class
@Injectable()
export class AlertService {
private subject = new Subject<any>();
constructor() {
}
public success(message: string) {
this.subject.next({type: 'success', text: message});
}
public error(message: string) {
this.subject.next({type: 'error', text: message});
}
public getMessage(): Observable<any> {
return this.subject.asObservable();
}
}
Component that receives the alert:
In this component you must inject the service into the constructor and subscribe to its Observable (Subject is a type of Observable), using the .subscribe()
method, then each time a new 'message' is sent it is detected and you can perform a certain action or assign that value to a variable, in your case the Class .
@Component({
})
export class AlertComponent implements OnInit, OnDestroy {
subscription: Subscription;
constructor(private alertService: AlertService){}
ngOnInit() {
this.subscription = this.alertService.getMessage().subscribe(message => {
if (message.text) {
switch (message.type) {
case 'success':
this.showSuccess(message.text);
break;
case 'error':
this.showError(message.text);
break;
}
}
});
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
Component that issues the alert:
In this component you must inject the service containing the Observable, and send the variable, in this particular example the message you want to show is sent and the service method already sets the notification type. In your case, just sending the new value of the Class would be enough.
@Component({
})
export class NotificationsComponent implements OnInit, OnDestroy {
constructor(private alertService: AlertService){}
ngOnInit() {
this.alertService.success('Exito al enviar mensaje');
}
Documentation:
You can find information about the Subject type here.
You can find more information about Angular Service here.