Is there a possibility when refreshing the page to save the tag that has been dynamically added ?
Now, the moment I refresh the page, while loading, the title tag changes to the original one, which I set in the index.html. When the page is loaded, the title tag then comes back to the correct one which is dynamically added. But, I want the title tag to stay the same while the page is refreshing.
This is my app.component.ts:
this.router.events.pipe(
filter((event) => event instanceof NavigationEnd),
map(() => this.activatedRoute),
map((route) => {
while (route.firstChild) route = route.firstChild;
return route;
}),
filter((route) => route.outlet === 'primary'),
mergeMap((route) => route.data)
)
.subscribe((event) => {
console.log(event)
this.translateService.get(event['title']).subscribe(name => {
this._seoService.updateTitle(name);
});
this._seoService.updateDescription(event['description'])
});
One approach is to make use of Local Storage to store your dynamic title in there. Here's a simple example where I am storing the title in Local storage and refreshing the page, and retaining my title back. Angular provides a service called Title that allows us dynamically update the title anytime.
<button (click)="setItem()">Click to set a title</button>
<p *ngIf="showInfo" >Refresh the page now :)</p>
export class AppComponent implements OnInit {
showInfo = false;
constructor(private titleService: Title) {}
ngOnInit() {
this.getItem();
}
setItem() {
localStorage.setItem('title', 'Hey World!');
this.showInfo = true;
this.getItem();
}
getItem() {
if (localStorage.getItem('title'))
this.titleService.setTitle(localStorage.getItem('title'));
else this.titleService.setTitle('No title');
}
}
Here's a live application.
Code - Stackblitz
Searched for a solution in other questions but nothing helped me..
I wish to redirect to url like,
this.router.navigateByUrl('/products');
In which i need to pass the array and need to get it it in the component which has the active link products using skip location change without showing anything in url.
Array will be like,
products = [{"id":1,"name":"Product One","id":2,"name":"Product Three","id":3,"name":"Product Six"}]
I need to pass this entire array in router link and need to retrieve it in another component (products) active link using skipLocation Change true..
Tried with sharedService but i am getting issue of data loading at right point of time and hence i decided to use via router link..
If this is not a good approach, kindly suggest other alternative without using sharedservice..
You can use Angular Services for a large data.
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
import { Subject } from 'rxjs/Subject';
#Injectable()
export class ExampleService {
private subject = new Subject<any>();
updateRouteData(data) {
this.subject.next(data);
}
routeData(): Observable<any> {
return this.subject.asObservable();
}
}
In your components;
For set route data;
import { ExampleService } from '/example.service'
export class ComponentOne{
constructor(private exampleService:ExampleService){
this.exampleService.updateRouteData(data)
}
You can pass data like;
import { ExampleService } from '/example.service'
export class ComponentTwo{
constructor(private exampleService:ExampleService){
this.exampleService.routeData().subscribe(data => {
console.log(data)
})
}
I am facing some trouble in relflecting in my parent component if an item has been enabled or not based on the selection made in the child component.
I am displaying my child content through a router-outlet.
Overall view: I have a side menu with several headers. Upon click on a header a view page will appear and within it a checkbox to allow the user to either enable or disable the menu header item.
What i want is when a user checks the box in the child component - that a check mark will appear next to the enabled header (without having to refresh the page - which is currently what is happening)
Parent component:
public ngOnInit() {
this.getMenuHeadersList();
}
private getMenuHeadersList() {
this.service.getMenuItemList(this.id).subscribe(
(data: MenuItems[]) => {
if (data !== undefined) {
this.menuList= data;
}
},
(error: any) => {
.....
});
}
//for loop menuItem of menuList
<a id="menuId" class="refine-menu-collapse" [routerLink]="[...]">
<span *ngIf="menuItem.isEnabled" class="win-icon win-icon-CheckMark"></span>
<span class="refine-menu-subtitle">{{menuItem.name}}</span>
</a>
the span where i check if menuItem.isEnabled is the checkmark that i would like to have appear once the user enables it from the child view componenet.
Child component:
public ngOnInit() {
this.getMenuHeadersList();
}
private onMenuItemValueChange(menuItem: MenuItemType, checked: boolean) {
menuItem.isEnabled = checked;
this.saveMenuItemTypes(menuItem);// makes a service call and calls getMenuHeadersList.
}
private getMenuHeadersList() {
this.service.getMenuItemList(this.id).subscribe(
(data: MenuItems[]) => {
if (data !== undefined) {
this.menuList= data;
this.singleMenuItem = this.menuItems.find((value) => value.menuItem.id === this.menuId);
}
},
(error: any) => {
.....
});
}
Child Html:
<input type="checkbox"
[checked]="menuItem?.isEnabled"(change)="onMenuItemValueChange(menuItem, $event.target.checked)">
<span class="text-body">title</span>
I have this feeling that i don't need to make the call to get the menuItems in the child component and i could get it from the parent but i am not sure how i am messing up myself.
You have not child/parent. The most easy way to do it, is use a variable in a service
If your service you has some like
checkedItems:any[]=[]
If your header
get checkedItems()
{
return yourservice.checkedItems;
}
<span *ngIf="checkedItems[i]" class="win-icon win-icon-CheckMark"></span>
In your component, somewhere
yourservice.checkedItems[index]=true
Is it possible to trigger a function that has a parameter in it like trigger(id) in ngOnInit?
I have a function that I want to trigger on (click) event as well as in ngOnInit so when the page first load it triggers basically the same function because it calls to the same API end-point.
function to be triggered in ngOnInit
getOrdersFromOrigin(id: number): void {
...
}
so in ngOnInit would be something like this maybe? its showing an error "Cannot find name 'id'"
ngOnInit() {
this.getOrdersFromOrigin(id);
}
Id is coming from my ngFor, its an Id of an item which I want to click (click)="getOrdersFromOrigin(id)"
You can handle it if its in route like param. For example if you are editing some record in table by clicking edit button then your app navigate to edit form you can handle it like this:
import { ActivatedRoute, Params, Router } from '#angular/router';
constructor(
private route: ActivatedRoute
) { }
ngOnInit() {
this.route.params.forEach((params: Params) => {
let id = +params['id']; // (+) converts string 'id' to a number
this.getOrdersFromOrigin(id);
});
}
getOrdersFromOrigin(id: number){
//some code
};
The param id is in getOrdersFromOrigin(), so it would not work in the scope of ngOnInit(), my suggestion is that you can declare a property id and marked it as #Input(). then you can use it outside. The codes is below:
export class SameComponent implement OnInit {
#Input() id:number=0; //initialize
getOrdersFromOrigin(id: number): void {
...
}
ngOnInit() { this.getOrdersFromOrigin(id);}
}
I have built an app that uses router 3.0.0-beta.1 to switch between app sections. I also use location.go() to emulate the switch between subsections of the same page. I used <base href="/"> and a few URL rewrite rules in order to redirect all routes to index.html in case of page refresh. This allows the router to receive the requested subsection as a URL param. Basically I have managed to avoid using the HashLocationStrategy.
routes.ts
export const routes: RouterConfig = [
{
path: '',
redirectTo: '/catalog',
pathMatch: 'full'
},
{
path: 'catalog',
component: CatalogComponent
},
{
path: 'catalog/:topCategory',
component: CatalogComponent
},
{
path: 'summary',
component: SummaryComponent
}
];
If I click on a subsection in the navigation bar 2 things happen:
logation.go() updates the URL with the necessary string in order to indicate the current subsection
A custom scrollTo() animation scrolls the page at the top of the requested subsection.
If I refresh the page I am using the previously defined route and extract the necessary parameter to restore scroll to the requested subsection.
this._activatedRoute.params
.map(params => params['topCategory'])
.subscribe(topCategory => {
if (typeof topCategory !== 'undefined' &&
topCategory !== null
) {
self.UiState.startArrowWasDismised = true;
self.UiState.selectedTopCategory = topCategory;
}
});
All works fine except when I click the back button. If previous page was a different section, the app router behaves as expected. However if the previous page/url was a subsection, the url changes to the previous one, but nothing happens in the UI. How can I detect if the back button was pressed in order to invoke the scrollTo() function to do it's job again?
Most answers I saw relly on the event onhashchange, but this event does not get fired in my app since I have no hash in the URL afterall...
I don't know if the other answers are dated, but neither of them worked well for me in Angular 7. What I did was add an Angular event listener by importing it into my component:
import { HostListener } from '#angular/core';
and then listening for popstate on the window object (as Adrian recommended):
#HostListener('window:popstate', ['$event'])
onPopState(event) {
console.log('Back button pressed');
}
This worked for me.
Another alternative for this issue would be to subscribe to the events emitted by the Angular Router service. Since we are dealing with routing, it seems to me that using Router events makes more sense.
constructor(router: Router) {
router.events
.subscribe((event: NavigationStart) => {
if (event.navigationTrigger === 'popstate') {
// Perform actions
}
});
}
I would like to note that popstate happens when pressing back and forward on the browser. So in order to do this efficiently, you would have to find a way to determine which one is occurring. For me, that was just using the event object of type NavigationStart which gives information about where the user is coming from and where they are going to.
To detect browser back button click
import platformlocation from '#angular/common and place the below code in your constructor :
constructor(location: PlatformLocation) {
location.onPopState(() => {
alert(window.location);
}); }
This is the latest update for Angular 13
You have to first import NavigationStart from the angular router
import { NavigationStart, Router } from '#angular/router';
Then add the following code to the constructor
constructor(private router: Router) {
router.events.forEach((event) => {
if(event instanceof NavigationStart) {
if (event.navigationTrigger === 'popstate') {
/* Do something here */
}
}
});
}
Angular documentation states directly in PlatformLocation class...
This class should not be used directly by an application developer.
I used LocationStrategy in the constructor
constructor(location: LocationStrategy) {
location.onPopState(() => {
alert(window.location);
});
}
A great clean way is to import 'fromEvent' from rxjs and use it this way.
fromEvent(window, 'popstate')
.subscribe((e) => {
console.log(e, 'back button');
});
Using onpopstate event did the trick:
window.addEventListener('popstate',
// Add your callback here
() => self.events.scrollToTopCategory.emit({ categId: self.state.selectedTopCategory })
);
I agree with Adrian Moisa answer,
but you can use "more Angular 2 way" using class PlatformLocation by injecting to your component or service, then you can define onPopState callback this way:
this.location.onPopState(()=>{
// your code here...
this.logger.debug('onpopstate event');
});
Simpler way - Link
import { PlatformLocation } from '#angular/common';
import { NgbModal } from '#ng-bootstrap/ng-bootstrap';
...
constructor(
private platformLocation: PlatformLocation ,
private modalService: NgbModal
)
{
platformLocation.onPopState(() => this.modalService.dismissAll());
}
I honestly don't know your use case. And the thread is quite old. But this was the first hit on Google. And if someone else is looking for this with Angular 2 and ui-router (just as you are using).
It's not technically detecting the back button. It's more detecting whether you as a developer triggered the state change or whether the user updated the URL themselves.
You can add custom options to state changes, this can be done via uiSref and via stateService.go. In your transitions, you can check whether this option is set. (It won't be set on back button clicks and such).
Using ui-sref
<a uiSref="destination-name" [uiOptions]="{custom: {viaSref: true}}">Bar</a>
Using state.go
import {StateService} from '#uirouter/core';
...
#Component(...)
export class MyComponent {
constructor(
private stateService: StateService
) {}
public myAction(): void {
this.stateService.go('destination-name', {}, {custom: {viaGo: true}});
}
}
You can detect it in any transition hook, for example onSucces!
import {Transition, TransitionOptions, TransitionService} from '#uirouter/core';
...
#Component(...)
export class MyComponent implements OnInit {
constructor(
private transitionService: TransitionService
) {}
public ngOnInit(): void {
this.transitionService.onSuccess({}, (transition: Transition) => this.handleTransition(Transition));
}
private handleTransition(transition: Transition): void {
let transitionOptions: TransitionOptions = transition.options();
if (transitionOptions.custom?.viaSref) {
console.log('viaSref!');
return;
}
if (transitionOptions.custom?.viaGo) {
console.log('viaGo!');
return;
}
console.log('User transition?');
}
}
You can check the size of "window.history", if the size is 1 you can't go back.
isCanGoBack(){
window.history.length > 1;
}