Angular 2 redirect on click

后端 未结 6 596
攒了一身酷
攒了一身酷 2020-12-15 20:20

How to create simple redirect on click on some button in Angular 2? Already tried:

import {Component, OnInit} from \'angular2/core\';
import {Router, ROUTER_         


        
相关标签:
6条回答
  • 2020-12-15 20:47

    You could leverage the event support of Angular2:

    import {Router} from '@angular/router';
    
    @Component({
      selector: 'loginForm',
      template: `
        <div (click)="redirect()">Redirect</div>
      `,
      providers: [ROUTER_PROVIDERS]
    })
    export class LoginComponent implements OnInit {
      constructor(private router: Router) { }
    
      redirect() {
        this.router.navigate(['./SomewhereElse']);
      }
    }
    
    0 讨论(0)
  • 2020-12-15 20:51

    in your html file right this code.

    <button (click)="btnClick()">Cancel</button>
    

    in your component.ts file right this code.

    constructor(private router:Router) { }
    btnClick(){
    this.router.navigateByUrl("/payment");
    }
    
    0 讨论(0)
  • 2020-12-15 20:52
    window.location.reload(); 
    

    does the trick

    0 讨论(0)
  • 2020-12-15 20:55

    Try routerLinkon button tag

     <button type="button"  [routerLink]="['/edit']">Edit</button>
    

    More Info

    0 讨论(0)
  • 2020-12-15 21:05

    I'd say use routerLink directive & placed that over a(anchor) tag

    <a [routerLink]="['./SomewhereElse']">Redirect</a>
    

    Also you need to remove ROUTER_PROVIDERS from providers & include it in bootstrap dependency and then add ROUTER_DIRECTIVES in directives option of component to use routerLink directive on HTML. Make sure RouterModule with its route has been injected in Main App module.

    0 讨论(0)
  • 2020-12-15 21:08

    I would make it more dynamic using method parameters

    Import the angular router

    import { Router } from '@angular/router';
    

    Create a button with click event

    <div (click)="redirect(my-page)">My page</div>
    

    Create a method with a pagename parameter

    redirect(pagename: string) {
      this.router.navigate(['/'+pagename]);
    }
    

    When clicked the router should route to the correct page

    0 讨论(0)
提交回复
热议问题