when i open my website i will see "Finance/voucher" on topenter image description here but when i refresh the page only "Finance" Appears and i don't want this i want when i refresh page still it will show "Finance/voucher" And all relevant code i have posted plz guide me which code i enter and where
export class TopBarComponent extends AppComponentBase {
formName = ""
constructor(
injector: Injector,
private _formTitleService: FormTitleService,
) {
super(injector);
}
ngOnInit() {
this.getFormTitle();
}
getFormTitle(){
this._formTitleService.getFormTitle()
.subscribe(name => {
this.formName = name;
});
}
Html code
<div class="page-title">
/ <span>{{formName}}</span>
</div>
You can set the initial value for formName = "Finance/voucher" in your component & it will be retained on page refresh.
Related
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
I'm having some problems to add a back home button in my top nav-bar. I want it to reset my page to the initial state of the page.
this is my header.component.html where I want to implement a function to go back to home page.
<div class="topnav">
<a class="active" routerLink="">{{title}}</a>
</div>
I tried routing to home, but my page got duplicated (Showing the same component twice) and I don't now what to do. My page can't have refresh either, because I'm doing this for a job and one of the requirements is having a full SPA. I tried too the function destroyPlataform(), then navigate back to path=" ", that worked, but my page refreshes when I do it and I can't have refresh on my page.
my app-routing.module:
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { MoviesComponent } from './movies/movies.component';
const routes: Routes = [{ path: '', component: MoviesComponent }];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}
I'm working with The Movie DB API, and in my page are some cards, it allows search for movies, multiple pages showing these cards and I need this home button to return to the first page, or to leave the search results.
I only have two components, the header.component that has the button to reset the current state of page and return to the initial state (not working) and the movies.component that show the movie cards, search for movies by name and have pagination. I need the back home function to reset the search name and return to the initial state of the application.
For more information of how I show my movies:
movies.component.ts:
//Showing page on application and redirection
getMovies(page: number) {
this.moviesService
.getMovies(this.movieName, this.currentPage)
.subscribe((paramName) => {
page = this.currentPage;
if (this.movieName) {
this.searchMovies(this.movieName, this.currentPage);
}
if (page) {
this.currentPage++ || this.currentPage--;
}
this.totalPages = (paramName as any).total_pages;
this.movies = (paramName as any).results;
});
}
//Search functions bellow
//search by query
searchMovies(query: string, page: number) {
this.moviesService.searchMovies(query, page).subscribe((response) => {
query = this.movieName;
page = 1;
this.totalResults = (response as any).total_results;
this.movies = [];
this.movies = response['results'];
});
}
//send value of query to the search function
queryListener(value: string): void {
this.movieName = value;
this.currentPage = 1 + 1;
this.searchMovies(value, 1);
}
//End of search functions
movies.service.ts:
//Redirects
getMovies(query: string = '', page: number) {
if ((query = '')) {
return this.discoverMovies(page);
}
if (query) {
return this.searchMovies(query, page);
}
return this.discoverMovies(page);
}
this next method is inside the movies.service.ts too, and I want to go back to him to see the discover cards when I click on the home button
//Show the list of movies more recent by popularity
discoverMovies(page: number) {
let discover = `${this.discoverUrl}?api_key=${this.apiKey}&language=${this.language}&sort_by=popularity.desc&include_adult=false&include_video=false&page=${page}`;
return this.http.get(discover);
}
A simple 'href="localhost:4200/"' would help, but when I use href the page refreshes. I hope someone can help me!
Try using:
<div class="topnav">
<a class="active" [routerLink]="['/']">{{title}}</a>
</div>
So say i have page one:
This page contains multiple variables and a constructor. it could look something like this:
export class TestPage implements OnInit {
testInt: number;
testString: string;
constructor(private someService: SomeService) {
}
ngOnInit() {
this.testInt = this.someService.getInt();
this.testString = this.someService.getLongText();
}
}
Now when this page loads it correctly sets the values.
Now say that I change page and on this page, I change some of the values in the service.
When I then come pack to this TestPage it hasn't updated the values.
Does this have something to do with caching? or with push state?
How can I make sure that the page is "reloaded" ?
Try using RxJS.
#Injectable({...})
class SomeService {
private _testInt: BehaviorSubject<number> = new BehaviorSubject<number>(0); // initial value 0
setTestInt(value: number) {
this._testInt.next(value);
}
getTestInt(): Observable<number> {
return this._testInt.asObservable();
}
}
#Component({...})
class TestPage implements OnInit {
public testInt: number;
public testInt$: Observable<number>;
private subscription: Subscription;
constructor(private someService: SomeService) {}
ngOnInit() {
// one way
this.testInt$ = this.someService.getTestInt();
// or another
this.subscription = this.someService.getTestInt()
.subscribe((value: number) => {
this.testInt = value;
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
in the HTML:
<p>{{ testInt }}</p>
<p>{{ testInt$ | async }}</p>
If you are subscribing to a Observable, make sure you unsubscribe after the usage (usually On Destroy lifecycle hook).
Async Pipe does that out of the box.
Or try the ionViewWillEnter lifecycle hook.
As you can see in the official documentation:
ngOnInit will only fire each time the page is freshly created, but not when navigated back to the page.
For instance, navigating between each page in a tabs interface will only call each page's ngOnInit method once, but not on subsequent visits.
ngOnDestroy will only fire when a page "popped". link That means that Page is cached, yes. Assigning value On Init will set the value only the first time page is visited and therefore not updated.
In my Angular project, I created a search box with a button to get a search result from another component. I have a router outlet in my App Component and I switch router outlet with the search result component using the search value variable. I use a service to share this search value variable between components. So, when I click on a link in html, the router outlet will appear. When I click on the search input and do a search, search result will appear. My problem is, when the router outlet is activated, I have to click twice on search button or hit twice enter key to appear the search result.
Code -
search.component.ts:
export class SearchComponent implements OnInit {
value: string;
constructor(private data: SendDataService){}
show: boolean = true;
showEl(){
this.show = true;
}
newValue() {
this.data.changeValue(this.value)
this.show = false;
}
ngOnInit(): void{
this.data.currentValue.subscribe(value => this.value = value)
}
}
search.component.html:
<input type="text" [(ngModel)]="value" (click)="showEl()" (keyup.enter)="newValue()" (input)="showEl()">
<button (click)="newValue()">Search</button>
search-result.component.ts:
export class SearchResultComponent implements OnInit {
_postsArray: = //JSON Object;
value: string = "";
filterarray: any[] = [];
constructor(private data: SendDataService){}
getData(){
this.data.currentValue.subscribe(value => {this.value = value;
this.showData();
})
}
showData(){
if (this.value != null){
this.filterarray=
this._postsArray.filter(f =>
f.title.toLowerCase()
.includes(this.value.toLowerCase()))
.map(searchname=>searchname.title)
}
}
ngOnInit(): void{
this.getData();
}
}
app.component.html:
<div>
<div *ngIf="!value">
<router-outlet></router-outlet>
</div>
<div *ngIf="value">
<app-search-result></app-search-result>
</div>
</div>
When I put {{value}} in app.component.html, it shows the value at the first click of search button. but <app-search-result> only appears in second click. How can I solve this?
I am calling a data service in an angular 2 component to load data on the ngOnInit() function. This component is placed on a Ionic tabs page. The ngOnInit() function is only called on initialization, but not on every navigation to the tab. I want to reload data from the data service on each navigation to the page, to refresh the component with the latest data.
How can I call a function in the component on each navigation to a tabs page?
This is my component:
#Component({
selector: 'reservation-list',
templateUrl: 'build/components/reservation-list.component.html',
bindings: [DataService, TimeService]
})
export class ReservationListComponent {
public items: any = [];
constructor(private dataService: DataService) { }
public ngOnInit() {
// this I want to call on each tab navigation!
this.items = this.dataService.getEvents();
}
}
My tabs are basically the ionic2-tabs example:
#Page({
templateUrl: 'build/pages/tabs/tabs.html'
})
export class TabsPage {
// this tells the tabs component which Pages
// should be each tab's root Page
tab1Root: any = Page1;
tab2Root: any = Page2;
tab3Root: any = Page3;
}
And the page is a basic ionic page where the component is insert:
<reservation-list></reservation-list>
#Page({
templateUrl: 'build/pages/page1/page1.html',
directives: [ReservationListComponent]
})
export class Page1 {
constructor() {
}
}
I think you can add a click event handler when you click your tabs and call that function.
In your tag
<a (click)="getEvents()"></a>
In you Component
getEvents() {
this.items = this.dataService.getEvents();
}
Please follow the life cycle of ionic and use below method inside tab child pages.
ionViewWillEnter()
{
//apply your code
}
This method will call always when you come on page.