简体   繁体   中英

Angular 6 routing using typescript function

I am trying to route programmatically through a function because I need a way around when clicking a link (a tag) inside an svg (since routerLink) does not work.

So far this is what I have:

    <g id="MenuStub4">
      <path
        id="box"
        fill="#231F20"
        d="M1171.088,420.473c0,4.307-4.387,7.799-9.795,7.799h-94.15c-5.408,0-9.793-3.492-9.793-7.799v-8.936
            c0-4.307,4.385-7.799,9.793-7.799h94.15c5.408,0,9.795,3.492,9.795,7.799V420.473z"
      />
      <text
        transform="matrix(1.3982 0 0 1 1096.8799 419.4614)"
        font-size="11.582"
      >
        <a fill="white" (click)="navigate()">
          Blog
        </a>
      </text>
    </g>

And the ts file:

import { Component } from "@angular/core";
import { Router } from "@angular/router";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  title = "BrainToBytes";

  constructor(private router: Router) {}

  navigate(): void {
    this.router.navigateByUrl("./blog");
  }
}

App-routing.module.ts:

import { BlogComponent } from './blog/blog.component';
import { NgModule, Component } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [{
  path: 'blog',
  component: BlogComponent
}];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

I checked the path, even if I change it with "/blog" it still doesn't work

I am a noobie with angular, so I am not sure if I am setting up the routing correctly or something else is wrong.

if your app-routing.module.ts represents something like this:

const routes: Routes = [{ path: 'blog', component: BlogComponent }];

if you are navigating through typescript try this:

this.router.navigate(['/blog']);

You cannot put a routerLink inside an svg, so don't try that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM