I am facing a very weird problem. I used Observable in *ngIf to display error along with the async pipe.
The problem is DOM is not updated when the value of Observable is updated. It updates only when I click on a page or it gets focus using the keyboard.
So, How should I bind Observable with DOM?
I tried various solutions for binding DOM using *ngIf, If else in *ngIf, with and without async Pipe, etc.
Here's how I used in HTML.
<div style="font-size: 0.9rem;" *ngIf="messageInfo | async"
[ngClass]="{ 'alert': message, 'alert-success': message.type === 'success',
'alert-danger': message.type === 'error' }">{{message.text}}
<span (click)="close()" style="cursor: pointer; float: right;">
<i class="material-icons icon-20 vertical-bottom">close</i>
</span>
</div>
Component Code
export class AlertComponent implements OnInit {
message: any;
messageInfo: Observable<any>;
constructor(private alertService: AlertService) {
}
ngOnInit() {
this.messageInfo = this.alertService.getMessage();
this.messageInfo.subscribe(message => {
this.message = message;
});
}
close() {
this.alertService.close();
this.message = undefined;
}
}
Service
export class AlertService {
private subject = new BehaviorSubject<any>(null);
private keepAfterNavigationChange = false;
constructor(private router: Router) {
// clear alert message on route change
router.events.subscribe(event => {
if (event instanceof NavigationStart) {
if (this.keepAfterNavigationChange) {
// only keep for a single location change
this.keepAfterNavigationChange = false;
} else {
// clear alert
this.subject.next(null);
}
}
});
}
success(message: string, keepAfterNavigationChange = false) {
this.keepAfterNavigationChange = keepAfterNavigationChange;
this.subject.next({type: 'success', text: message});
// to hide message after 3 seconds.
setTimeout(() => {
this.close();
}, 3000);
}
error(message: string, keepAfterNavigationChange = false) {
this.keepAfterNavigationChange = keepAfterNavigationChange;
this.subject.next({type: 'error', text: message});
// to hide message after 3 seconds.
setTimeout(() => {
this.close();
}, 3000);
}
getMessage(): Observable<any> {
return this.subject.asObservable();
}
close() {
this.subject.next(null);
}
}
I use it in all the other components this way:
<alert></alert>
I expect to update UI according to the value of Observable without clicking or focusing on the page. Unfortunately, it gets updated only when I focus on the page using a mouse or keyboard.