Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(router): new output that would notify when link is activated #43280

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions goldens/public-api/router/router.md
Expand Up @@ -549,6 +549,7 @@ export class RouterLinkActive implements OnChanges, OnDestroy, AfterContentInit
constructor(router: Router, element: ElementRef, renderer: Renderer2, cdr: ChangeDetectorRef, link?: RouterLink | undefined, linkWithHref?: RouterLinkWithHref | undefined);
// (undocumented)
readonly isActive: boolean;
readonly isActiveChange: EventEmitter<boolean>;
// (undocumented)
links: QueryList<RouterLink>;
// (undocumented)
Expand Down
22 changes: 21 additions & 1 deletion packages/router/src/directives/router_link_active.ts
Expand Up @@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/

import {AfterContentInit, ChangeDetectorRef, ContentChildren, Directive, ElementRef, Input, OnChanges, OnDestroy, Optional, QueryList, Renderer2, SimpleChanges} from '@angular/core';
import {AfterContentInit, ChangeDetectorRef, ContentChildren, Directive, ElementRef, EventEmitter, Input, OnChanges, OnDestroy, Optional, Output, QueryList, Renderer2, SimpleChanges} from '@angular/core';
import {from, of, Subscription} from 'rxjs';
import {mergeAll} from 'rxjs/operators';

Expand Down Expand Up @@ -99,6 +99,23 @@ export class RouterLinkActive implements OnChanges, OnDestroy, AfterContentInit
*/
@Input() routerLinkActiveOptions: {exact: boolean}|IsActiveMatchOptions = {exact: false};

/**
*
* You can use the output `isActiveChange` to get notified each time the link becomes
* active or inactive.
*
* Emits:
* true -> Route is active
* false -> Route is inactive
*
* ```
* <a
* routerLink="/user/bob"
* routerLinkActive="active-link"
* (isActiveChange)="this.onRouterLinkActive($event)">Bob</a>
* ```
*/
@Output() readonly isActiveChange: EventEmitter<boolean> = new EventEmitter();

constructor(
private router: Router, private element: ElementRef, private renderer: Renderer2,
Expand Down Expand Up @@ -163,6 +180,9 @@ export class RouterLinkActive implements OnChanges, OnDestroy, AfterContentInit
this.renderer.removeClass(this.element.nativeElement, c);
}
});

// Emit on isActiveChange after classes are updated
this.isActiveChange.emit(hasActiveLinks);
}
});
}
Expand Down
46 changes: 45 additions & 1 deletion packages/router/test/integration.spec.ts
Expand Up @@ -4662,6 +4662,44 @@ describe('Integration', () => {
fixture.detectChanges(false /** checkNoChanges */);
expect(TestBed.inject(NgZone).hasPendingMicrotasks).toBe(false);
}));

it('should emit on isActiveChange output when link is activated or inactivated',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);

router.resetConfig([{
path: 'team/:id',
component: TeamCmp,
children: [{
path: 'link',
component: DummyLinkCmp,
children: [{path: 'simple', component: SimpleCmp}, {path: '', component: BlankCmp}]
}]
}]);

router.navigateByUrl('/team/22/link;exact=true');
advance(fixture);
advance(fixture);
expect(location.path()).toEqual('/team/22/link;exact=true');

const linkComponent =
fixture.debugElement.query(By.directive(DummyLinkCmp)).componentInstance as
DummyLinkCmp;

expect(linkComponent.isLinkActivated).toEqual(true);
const nativeLink = fixture.nativeElement.querySelector('a');
const nativeButton = fixture.nativeElement.querySelector('button');
expect(nativeLink.className).toEqual('active');
expect(nativeButton.className).toEqual('active');


router.navigateByUrl('/team/22/link/simple');
advance(fixture);
expect(location.path()).toEqual('/team/22/link/simple');
expect(linkComponent.isLinkActivated).toEqual(false);
expect(nativeLink.className).toEqual('');
expect(nativeButton.className).toEqual('');
})));
});

describe('lazy loading', () => {
Expand Down Expand Up @@ -5928,15 +5966,21 @@ class AbsoluteLinkCmp {
@Component({
selector: 'link-cmp',
template:
`<router-outlet></router-outlet><a routerLinkActive="active" [routerLinkActiveOptions]="{exact: exact}" [routerLink]="['./']">link</a>
`<router-outlet></router-outlet><a routerLinkActive="active" (isActiveChange)="this.onRouterLinkActivated($event)" [routerLinkActiveOptions]="{exact: exact}" [routerLink]="['./']">link</a>
<button routerLinkActive="active" [routerLinkActiveOptions]="{exact: exact}" [routerLink]="['./']">button</button>
`
})
class DummyLinkCmp {
private exact: boolean;
public isLinkActivated?: boolean;

constructor(route: ActivatedRoute) {
this.exact = route.snapshot.paramMap.get('exact') === 'true';
}

public onRouterLinkActivated(isActive: boolean): void {
this.isLinkActivated = isActive;
}
}

@Component({selector: 'link-cmp', template: `<a [routerLink]="['/simple']">link</a>`})
Expand Down