@ngx-href
A library that allows href to understand Angular's router while retaining its default functionality.
- Use
router.navigate()
for internal link - Support scroll with the
#
attributes and let you configure the scrolling logic - Automatically append
rel="nooepener"
& target="_blank"
to external link if wished so - Support using
href
with the html button
attribute
Installation
npm install ngx-href
Inside your app.module.ts
file.
import { ngxHrefModule, ngxHrefService } from 'ngx-href'
imports: [
ngxHrefModule.forRoot({}),
ngxHrefModule.forRoot({
avoidSpam: true,
behavior:"smooth",
defaultOffset:"30",
navbarOffset:"60",
rel:"noopener nofollow",
target:"_blank",
}),
],
Angular routing
Nothing to do it should work out of the box
Avoid Spam
- Change the
href
from the DOM from example@outlook.com
into example(at)outlook.com
- Let js handle the click event.
Scroll logic
Behavior
Default: "auto"
Accepted value: ScrollBehavior
// ("auto" | "instant" | "smooth")
Can also be passed individually directly through html
<a href="https://my-external-url.com" behavior="instant">
defaultOffset
The standard offset to be added to your website scrollTo
logic
Default: 0
Accepted value: number
Together with the navbarOffset
will be the total offset for the scroll.
navbarOffset
An additional offset calculated base on your navbar height
Default: 0
Accepted value: number
Together with the defaultOffset
will be the total offset for the scroll.
You can update this value after the navbar is rendered.
<navbar #navbar>
</navbar>
@ViewChild('navbar', { static: true }) navbar: ElementRef
constructor(
private _ngxHrefService: NgxHrefService,
) {}
ngAfterContentInit(): void {
this._ngxHrefService.navbarOffset = this.navbar.nativeElement.offsetHeight
}
External link
Rel attribute
Default: undefined
Accepted value: string
Can also be passed individually directly through html
<a href="https://my-external-url.com" rel="noopener nofollow">
Target attribute
Default: "_self"
Accepted value: string
Can also be passed individually directly through html
<a href="https://my-external-url.com" target="_blank">
target attribute
Usage
Wherever you plan to use the href directive
import { ngxHrefModule } from 'ngx-href'
imports: [
ngxHrefModule,
]
Then you can use it as you would normally use an a
element
Directive
Normal use
<a href="/angular/router/link">
My internal link
</a>
<button href="/angular/router/link">
My internal link
</button>
<a href="https://external-url.com">
An external link
</a>
<a href="#myAnchor">
My scroll to anchor
</a>
<a href="/angular/router#link">
My internal link with anchor
</a>
Service
import { ngxHrefService } from 'ngx-href'
constructor(public ngxHrefService: ngxHrefService) {}
Normal use
<button (click)="ngxHrefService.scrollTo(#myAnchor)">
Scroll to #myAnchor
</button>
<h2 id="myAnchor">A title</h2>
Authors and acknowledgment