Search code examples
angulartypescriptangular8angular-routing

How to Create Angular Internal URL Hyperlink?


How do I create URL for an internal link?

Say user in on Customer Component page, and wants to go to Product page.

http://localhost:4200/app/customer

There is textbox in the Component which states Product: How can they route to Product Page in Angular Typescript and HTML?

http://localhost:4200/app/product/{ProductName}

http://localhost:4200/app/product/ComputerKeyboard

http://localhost:4200/app/product/Book

The baseURL may change also, depending on port numbers, environment eg:

http://www.TestEStore.com/app/product/ComputerKeyboard

http://www.TestEStore.com/app/product/Book

Its also needs to do html encoding, since html encoding eg spaces are encoded as %20, etc

Trying to edit code :

let productName: string = 'Computer Keyboard';

<a href="{{Whats the variable name?}}/product/{{this.productName)}}">Computer Keyboard</a>

Is there better option in Angular?

Resource: How to create a link to external URL in Angular 2


Solution

  • This is what you should do:

    <a [routerLink]="['/app/product/', productName]">Product</a>
    

    Use the routerLink directive so the angular router can navigate to the proper component. Don't use href attribute on for internal links as that will do a full postback which will reload your application.