Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

Back button directive Angular

/** Navigation service ***/

import { Injectable } from '@angular/core'
import { Location } from '@angular/common'
import { Router, NavigationEnd } from '@angular/router'

@Injectable({ providedIn: 'root' })
export class NavigationService {
  private history: string[] = []

  constructor(private router: Router, private location: Location) {
    this.router.events.subscribe((event) => {
      if (event instanceof NavigationEnd) {
        this.history.push(event.urlAfterRedirects)
      }
    })
  }

  back(): void {
    this.history.pop()
    if (this.history.length > 0) {
      this.location.back()
    } else {
      this.router.navigateByUrl('/')
    }
  }
}


/** create directive ****/

import { Directive, HostListener } from '@angular/core'
import { NavigationService } from './navigation.service'

@Directive({
  selector: '[backButton]',
})
export class BackButtonDirective {
  constructor(private navigation: NavigationService) {}

  @HostListener('click')
  onClick(): void {
    this.navigation.back()
  }
}

/*** use below code to use directive **/

<button backButton>Back with NavigationService</button>
Comment

PREVIOUS NEXT
Code Example
Javascript :: jquery to vanilla js converter 
Javascript :: how to use adminlte in reacts 
Javascript :: use recursation in iife in js 
Javascript :: Minimize DOM access - JavaScript 
Javascript :: install react-foundation library in react js 
Javascript :: json data from server into html table 
Javascript :: detect click on link in all places javascript 
Javascript :: count all items inside 2nd ul using jquery 
Javascript :: z-song laravel-admin unable load js fucntion untill use f5 
Javascript :: hooks in bdd 
Javascript :: safe check in js 
Javascript :: how to push an object into an array in reducer 
Javascript :: mongodb match array not empty aggregation 
Javascript :: 3.4.2. Two Special Characters¶ 
Javascript :: firebase dynamic Links safari not able to open the link becuse the link is invalid 
Javascript :: how to share variables between routes node 
Javascript :: enquirer confirm 
Javascript :: Cannot load gulp: ReferenceError: primordials is not defined 
Javascript :: javascript substtgin 
Javascript :: 10.4.2. Functions // Default Value 
Javascript :: faker link for json post req 
Javascript :: multiple confition checking jasvascript 
Javascript :: underscore javascript 
Javascript :: Unexpected eval or arguments in strict mode 
Javascript :: textfield extjs retrinjir a 4 caracteres 
Javascript :: Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout. 
Javascript :: change iphone return in keyboard to search in react native 
Javascript :: blank array condition in react js 
Javascript :: jquery select text with event target 
Javascript :: react js averta fonts not working in safari staging deployement 
ADD CONTENT
Topic
Content
Source link
Name
2+6 =