When I go to a new routing page in HTML, how do I reload the new page in HTML?
<button ion-button routerLink="/desiredRoute" routerDirection="root">
edit:
I am trying to pass variables from another page.
Page1.ts: variables I want variables from
Page2.ts: variables I want to display from page1
If I load page 2, then go into page1 and change the variables, Page2 variables don't change unless I reload.
Solved:
added this to my .ts
constructor(private route: ActivatedRoute) { }
ngOnInit(): void {
this.route.params.subscribe(
params => {
/*Update Variables here*/
}
);
}
keep in mind, any variables you set in one page, are not going to be available in the second page after you route. you have 2 possible solutions:
1) Use queryParams to pass basic strings or numbers as variables through your route, which will show up on the url and can be parsed. (usually to pass an itemId or something very simple)
2) set variable values using localStorage, and then look them up after routing.
Related
I'm currently learning Web Components and I wonder if it is possible to have a Component load its own data dynamically, similar to how <img> does from its src attribute, i.e. something like this:
<my-fancy-thingy src='/stuff.json'></my-fancy-thingy>
Obviously this functionality would be useful if stuff.json could be rather large, so it should also be possible to make use of the browser's caching mechanism so the referenced file doesn't get reloaded every time we request the page, unless changed.
Can this be done?
Sure, take inspiration from <load-file> See Dev.to Post
/*
defining the <load-file> Web Component,
yes! the documenation is longer than the code
License: https://unlicense.org/
*/
customElements.define("load-file", class extends HTMLElement {
// declare default connectedCallback as sync so await can be used
async connectedCallback(
// attach a shadowRoot if none exists (prevents displaying error when moving Nodes)
// declare as parameter to save 4 Bytes: 'let '
shadowRoot = this.shadowRoot || this.attachShadow({mode:"open"})
) {
// load SVG file from src="" async, parse to text, add to shadowRoot.innerHTML
shadowRoot.innerHTML = await (await fetch(this.getAttribute("src"))).text()
// append optional <tag [shadowRoot]> Elements from inside <load-svg> after parsed <svg>
shadowRoot.append(...this.querySelectorAll("[shadowRoot]"))
// if "replaceWith" attribute
// then replace <load-svg> with loaded content <load-svg>
// childNodes instead of children to include #textNodes also
this.hasAttribute("replaceWith") && this.replaceWith(...shadowRoot.childNodes)
}
})
Change .text() to .json() and it parses JSON files
Caching can be done by storing the String in localStorage (but a 5MB limit total, I think):
https://en.wikipedia.org/wiki/Web_storage
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
You need to come up with "data has changed" strategy; as the Client has no clue when data actually was changed. Maybe an extra semaphore file/endpoint that provides info if the (large) JSON file was changed.
This works like a charm
export class MonElement extends HTMLElement {
constructor(){
super();
this.attachShadow({mode:'open'});
(...)
this.shadowRoot.appendChild(atemplate);
}
connectedCallback(){...}
static get observedAttributes(){
return ['src'];
}
attributeChangedCallback(nameattr,oldval,newval)
{
if (nameattr==='src') {
this[nameattr]=newval;
here do the fetch for the src value which is newval then update what you got in the innerdom
}
(...)
Somehow I find this hard to describe, but here I go:
I have a div in my SelectClasses Razor view page with an id="id152".
In order for me to show that div on the page at reload, I have to add the suffix #id152 to my page url.
<div id="id152">blabla</div>
...
..
Section 7
Now my question: Is there a way to add/pass this suffix to a 'RedirectToAction()'?
public ActionResult Index()
{
//All we want to do is redirect to the class selection page and add a suffix
return RedirectToAction("SelectClasses", "Registration", new { id = 99 })); //add suffix here somewhere
}
So when my SelectClasses view is shown, the url looks something like this:
'[url]/SelectClasses/99#id152'
The RedirectToActionResult (among the rest of RedirectTo* results) is meant to be used for generation of URLs based on registered routing data.
In your case, you wish to concatenate a hash parameter value (#id152) that is not being sent to the server and only used by the browser. That's why said methods don't bother dealing with it.
I suggest you do this instead:
var redirUrl = Url.Action("SelectClasses", "Registration", new { id = 99 });
redirUrl = String.Concat(redirUrl, "#id152");
return Redirect(redirUrl);
I am using Angular 6 and see in home.component.ts file variable being defined at the beginning: public hasResults = false;
And then in home.component.html file - section for displaying:
<span style="padding-left:5px" [hidden]="hasResults">
<ang-shortcut-display></ang-shortcut-display>
</span>
(which will display section once hasResults is not False anymore).
Now I need to have action on a Home Button to hide section again (I am assuming to set hasResults to False again).
How to set this variable hasResults to False again when e.g. someone hits Home button.
So far I found that action after hitting Home Button is in home.component.ts
homeRouteAction() {
\\ set hasResults to false
}
but not sure if hasResults is visible at that moment and how properly to set it to false (pass value) so that can change value (and set above html section to hidden again)?
for this, you have two things you can pass this value in service or maintain local storage,
when you initiate this value that time you can call set value in service and when you need to call get user service using observable, rxjs
You can set a method in your home.component.ts
setResults () {
this.hasResults=false;
}
and then, in the home.component.html call the method for it to propagate
(click)="setResults()"
Such as:
Home
Is it possible to customize the back behavior of the Angular router? Specifically, I'd like to add a URL fragment based on the resource the browser is navigating from.
For example, if the browser is on http://example.com/purchases/42, navigating back would take the user to http://example.com/purchases#42 instead of http://example.com/purchases. This is desirable because the /purchases page could be very long, and the URL fragment could position the browser in the context of the previous page.
Is such a thing even possible? Is the only way this could be accomplished is by using the History API, or is there some other API that Angular users for managing navigation state?
Well, lucky for you, in the new Angular 6.1 there is a new feature for routers that you can enable and your router will "remember" your last scroll position when you hit back.
You have to set the routers module like that:
RouterModule.forRoot(routes, {
scrollPositionRestoration: 'enabled'
})
There problem right now is that its a very new feature, and its will only work for static pages. Thats mean that if you fetching content from service or something, the restoration will try to set it self before you actually have the data, so the position will fail. (Currently, it will also fail even if you are using a resolver)
There is a workaround that we can use right now via the new service called viewportScroller from the #angular/router package, but you will have to do it manully. (currently, it will probably get fixed in the near future).
export class PendingRacesComponent {
scrollPosition: [number, number];
races: Array<RaceModel>;
constructor(route: ActivatedRoute, private router: Router, private viewportScroller: ViewportScroller) {
this.races = route.snapshot.data['races'];
this.router.events.pipe(
filter(e => e instanceof Scroll)
).subscribe(e => {
if ((e as Scroll).position) {
this.scrollPosition = (e as Scroll).position;
} else {
this.scrollPosition = [0, 0];
}
});
}
ngAfterViewInit() {
this.viewportScroller.scrollToPosition(this.scrollPosition);
}
}
This is an example of how you can use it right now, for full explanation you should visit the post
I want to know how can I get the route values in Razor Pages (Page.cshtml).
Ex.
https://localhost:44320/AdminPanel/Admins
if I was using MVC i would get these datas as
var controller = ViewContext.RouteData.Values["Controller"]; //AdminPanel
var action = ViewContext.RouteData.Values["Action"]; //Admins
How can i get these values in Razor Pages?
For anyone trying to get it you can get it by:
var fullRoute = ViewContext.RouteData.Values["Page"]; // AdminPanel/Admin
Assuming you have a page named AdminPanel.cshtml in your Pages folder, add a parameter after #page on the first line, like this:
#page "{action}"
Then in the code behind (AdminPanel.cshtml.cs), add a prop and a parameter to your OnGet method like so:
private string _action;
public void OnGet(string action) {
_action = action; //now do whatever you want with it
}
You can add a getter if you want to access it in your model back on the cshtml page.
Note: doing the above will make that page require an action be specified. Alternatively, you can also make it optional by adding a question mark (#page "{action?}") and setting a default value in your OnGet (OnGet(string action="")).