I have a problem with handle back button in browser. I have a custom modal(just html/css, no bootstrap), and I want to show this modal when user click back button. If user choose Yes, browser will directly to previous page. When user choose No, the modal will disappear and not directly to another. I tried using candeactive and PlatformLocation, but it seem not work. I can't stop browser directly to previous page when click. Have any solution for this? If yes, please give me an example. Thanks all for help!
This is my code:
article.component.html
<div class="editor-page">
<div class="container">
<div class="row">
<div class="col-md-8 offset-md-2">
<form [formGroup]="articleForm" (ngSubmit)="handleSubmit()">
<div class="form-group">
<input type="text" name="title" class="form-control" placeholder="Article Title" formControlName="title">
</div>
<div class="form-group">
<input type="text" name="body" class="form-control" placeholder="What's this article about?" formControlName="body">
</div>
<div class="form-group">
<textarea name="description" class="form-control" id="" cols="30" rows="10" placeholder="Write your article (in markdown)" formControlName="description"></textarea>
</div>
<div class="form-group">
<input type="text" name="tagList" class="form-control" placeholder="Enter tags" formControlName="tagList">
</div>
<button class="btn btn-md btn-success float-right">Publish Article</button>
</form>
</div>
</div>
</div>
</div>
<div class="modal" *ngIf="isBackClicked">
<p>Do you want to quite?</p>
<a (click)="handleYesBtn()">Yes</a>
<a (click)="handleNoBtn()">No</a>
</div>
article.component.ts
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { ArticleService } from '../../services/article.service';
import { ArticlePost } from '../../models/article';
import { Location } from "@angular/common";
import { Subscription } from 'rxjs/Subscription';
import { PlatformLocation } from '@angular/common'
import { Router } from '@angular/router';
@Component({
selector: 'app-article',
templateUrl: './article.component.html',
styleUrls: ['./article.component.scss']
})
export class ArticleComponent implements OnInit {
isBackClicked = false;
articleForm: FormGroup;
subscription: Subscription;
constructor(
private formBuilder: FormBuilder,
private articleService: ArticleService,
private router: Router,
private location: PlatformLocation
) {
this.articleForm = this.formBuilder.group({
title: "",
body: "",
description: "",
tagList: null
})
location.onPopState(() => {
this.isBackClicked = true;
});
}
ngOnInit() {
}
handleYesBtn() {
this.router.navigateByUrl('/');
}
handleNoBtn() {
this.isBackClicked = false;
}
handleSubmit() {
const article = new ArticlePost(this.articleForm.value);
this.articleService.addArticle(article).subscribe(data => {
console.log('data', data);
})
}
}
When I clicked back button in browser, it's not show my modal and directly to previous page.