Angular 2 Page / Component not reloading - javascript

Using the Nav on the website and going from
http://localhost:4200/mens
to
http://localhost:4200/mens/shirts
Works fine but when clicking on another category from with shirts like Hats the component/page doesn't reload and i'm unsure why as i'm not getting a error and it work fine when you click in the first category but within that category if you click on another it doesn't.
const routes: Routes = [
{
path : '',
component: WebsiteComponent,
children: [
{
path : '',
component: HomePageComponent,
},
{
path : 'mens',
component: MensPageComponent
},
{
path : 'mens/:category',
component: MensPageComponent
}
]
}
];

How are you getting your params in the men's component?
Here is a stackblitz that works https://stackblitz.com/edit/angular-buahdy
It uses route.params observable that emits when the route changes, if you are using a snapshot it will not change as it is not an observable.
category$ = this.route.params.pipe(map(params => params.category));
constructor(private route: ActivatedRoute) { }
and in the template show the category with the async pipe
Category {{ category$ | async }}
When you go from mens/shoes to mens/shirts the men's component does not reload, only the category param has changed. Subscribing to the param with route.params is how you trigger an update in your component.

When using the children property in the route. The component will need a router-outlet for those children routes to be rendered.
WebsiteComponent template:
<!-- some code -->
<!-- where children routes are rendered -->
<router-outlet></router-outlet>

Related

Angular Nested Child Routing

I am learning use of multiple router-outlet.
While using navigateBy function of router, i am not able to view my child route and getting error. But if i access it via routerLink in html i get the desired output.
So in below code, navigation to songs is working , but navigation to films is not.
const routes = [
{
path: 'bollywood',
component: BollywoodComponent,
children: [
{
path: 'films',
component: FilmsComponent,
},
{
path: 'songs',
component: SongsComponent,
},
],
},
{
path: 'hollywood',
component: HollywoodComponent,
},
{
path: 'tollywood',
component: TollywoodComponent
},
];
App Component html
<button class="f-margin-16" (click)="navigateToBollywoodSection()"> Bollywood </button>
<button class="f-margin-16" (click)="navigateToHollywoodSection()"> Hollywood </button>
<button class="f-margin-16" [routerLink]="['tollywood']" > Tollywood </button>
<br>
Router outlet starts now
<router-outlet> </router-outlet>
Bollywood Component html
<button (click)="navigateToFilms()"> Films </button>
<button [routerLink]="['songs']"> Songs </button>
<router-outlet> </router-outlet>
navigateToFilms() {
this.router.navigate(['/films']);
}
StackBitz Link
https://stackblitz.com/edit/angular-ivy-1nzkus?file=src/app/bollywood/bollywood.component.html
In router.navigate, you can pass relativeTo as the second param.
navigateToFilms() {
this.router.navigate(['films'], {relativeTo: this.activatedRoute} );
}
This way navigation will happen relative to the current route.
In the constructor you can add the ActivatedRoute dependency.
constructor(private activatedRoute: ActivatedRoute) {}
If you use <button [routerLink]="['songs']"> Songs </button>, the navigation by default happens relative to the current route.
Use it like this
this.router.navigate(['bollywood/films']);
If you want to use a navigation route then you can use this code.
because without a specific parent route you can't access child routing.
this.router.navigate(['/bollywood/films']);

Angular 14: Routing to child route not working properly

In my Angular 14 application I have tree on the left side which contains buildings and persons inside these buildings.
+ Building 1
- Person 1
- Person 2
- Person 3
+ Building 2
- Person 4
- Person 5
When I click an entry in the tree I want to display some details on the right side of the browser window. Therefore, I created a HTML template which contains the tree and a <router-outlet> for rendering the child components.
<div class="container">
<div class="tree-container">
...
</div>
</div>
<div class="content-container">
<router-outlet></router-outlet>
</div>
</div>
The routes are defined in this way:
const routes: Routes = [
{ path: '', component: MainComponent, canActivate: [AuthGuard],
children: [
{ path: 'building/:uuid', component: BuildingComponent},
{ path: 'person/:uuid', component: PersonComponent},
]
},
];
When I click an entry I call a method in the Maincomponent routing to the corressponding child compoment:
this.router.navigate(['building', buildingUuid], {relativeTo: this.route})
or
this.router.navigate(['person', personUuid], {relativeTo: this.route})
This works fine if I switch between building and person items. In this case the child component is shown in the right part of the browser window.
But when I click two nodes of the same type after each other (e.g. Person 1 and then Person 2) I see that the URL in the browser changes, but the child component is not updated.
Any ideas, what I'm doing wrong?
It's because you are already navigated to that component, so the component is already created and will not be created again.
What you should do is to subscribe to the params in the ngOnInit, so your logic will be executed on each param change:
import { ActivatedRoute} from '#angular/router';
...
constructor(private route: ActivatedRoute) {}
...
ngOnInit() {
this.route.params.subscribe({
next: (params) => {
const uuid = params.uuid;
// Your logic
},
error: (error) => {
console.log('ERROR: ', error);
},
});
}
Note: Don't forget to unsubscribe from Observable in ngOnDestroy.

Why is component props undefined (vue router)

I am new to Vue and I'm trying to learn how to apply Vue router. I got normal routing to work no problem. When I try to use dynamic routing everything continued to work fine. When I tried to pass props to dynamic routes however my code breaks.
I'm using these cdn versions of Vue and Vue router which are the versions suggested by the official websites:
- https://cdn.jsdelivr.net/npm/vue#2.5.16/dist/vue.js
- https://unpkg.com/vue-router#2.0.0/dist/vue-router.js
The HTML
<div id="app">
<h1>{{ message }}</h1>
<nav>
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
<router-link to="/user/John">Name</router-link>
</nav>
<!-- route outlet -->
<!-- component matched by route will render here -->
<router-view></router-view>
</div>
The JS
// Route components
const Home = { template: '<div>Home</div>' };
const About = { template: '<div>About</div>' };
const User = { props: ['name'], template: `
<div>
<div>User {{ name }}</div>
<button #click="checkName">Check</button>
</div>`,
methods: {
checkName: function() {
console.log('Params name: ' + this.$route.params.name);
console.log('Props name: ' + this.name);
}
}
};
// Routes for router
const routes = [
{ path: '/', component: Home },
{ path: '/home', redirect: Home },
{ path: '/about', component: About },
{ path: '/user/:name', component: User, props: true }
];
const router = new VueRouter({
routes: routes
});
const app = new Vue({
el: '#app',
data: {
message: 'VueJS Router'
},
router: router
});
When I navigate to the 'Name' page the static text renders fine but the dynamic text fails to load. I added a button that will log the value of name from props and from $route.params to the user. When clicked it turns out that the value of name in props is undefined but the value of name from params is correct. Why is this?
If you're sticking with VueRouter#2.0.0 or lower :
The name that you expect is not passed as a prop but as a route param, cf. Dynamic route matching.
You need to access it from your template as follow : $route.params.name.
You could also use a computed value instead.
If you can update VueRouter
As stated in another answer, and according to the release note of VueRouter#2.2.0, passing down route params as props has only been introduced in v2.2.0, you were using v2.0.0. If you would like to use props you would need to update to (at least) v2.2.0.
CDN link provided on the Vue Router installation page was outdated. Instead of:
https://unpkg.com/vue-router#2.0.0/dist/vue-router.js
use:
https://unpkg.com/vue-router#3.0.1/dist/vue-router.js
Answer provided here:
https://forum.vuejs.org/t/why-is-component-props-undefined-vue-router/34929/5

how to have nested child route in angularjs 2 using ID

My sample Demo
i"m new in angularjs 2
how to show twitter names for corresponding names using routes in same page using second <router-outlet></router-outlet>
tried routing for child one (sample one not for this app)
children: [{path: 'child-one', component: ApplicationSecondComponent},
First of all you need to have default child route, so use next route configuration:
export const AppRoutes: Routes = [
{ path: '', component: ContactsListComponent, children: [{
path: '',
component: ContactsDetailComponent
}, {
path: 'contact/:id',
component: ContactsDetailComponent,
resolve: {
contact: 'contact'
}
}]
}
];
So you should control contact empty state using *nfIf directive also in your details component
<div *ngIf="contact">
<h2>{{contact.name}}</h2>
<dl>
<dt>Twitter</dt>
<dd>{{contact.twitter}}</dd>
</dl>
<p><a routerLink="/">Back to list</a></p>
</div>
And additional routing outlete inside list template
<ul>
<li *ngFor="let contact of contacts | async">
<a [routerLink]="['contact', contact.id]">{{contact.name}}</a>
</li>
</ul>
<router-outlet></router-outlet>
Also be careful - you need to move your contact resolve login into details component as you need to react to url params chages. This code will works only one:
this.contact = this.route.snapshot.data['contact'];
Please review updated plunker https://plnkr.co/edit/ZgbBKaF58brxILueKkxv?p=preview

Vue-router reload components

I have a few routes that each load 3 components. Two of the components are the same on all routes.
When I move between those routes I want to pass new data and on some init event of the component I want to fill the data of that component so it reflects on the UI.
Also I want to retrigger bootstrap animations of components being loaded.
How would I go about doing that.
Because right now, I don't know where in the component lifecycle would I fetch the data and rerender the component with this new data.
Concretly in myapps/1 and /newapp/ I have a main view component and a sidebar component. In the /newapp/ URL I want all icons on the sidebar to be red (nothing on the main view has been filled) and the main view should be empty.
On the myapps/1 I want to load the data from the server into the main view and if it's all filled I want icons on the sidebar to be green.
What now happens I load myapps/1, click on the second item in the sidebar and the main view changes to the second view. Then I router.push("/newapp/); and sidebar stays on the second item and second main view.
So router.push("/myapps/"); doesn't reload my sidebar and my main view.
EDIT:
Here you see my routes, sidebars and default are the same.
const routes = [
{
path: "/myapps/newproject",
components: {
default: ProjectMain,
"breadcrumbs": BreadcrumbsNewProject,
"sidebar": SidebarProject,
}
},
{
path: "/myapps/:id",
components: {
default: ProjectMain,
"breadcrumbs": BreadcrumbsCurrentProject,
"sidebar": SidebarProject,
}
},
{
path: "/myapps/newversion/:id",
components: {
default: ProjectMain,
"breadcrumbs": BreadcrumbsNewVersion,
"sidebar": SidebarProject,
}
}
];
This is my ProjectMain.vue
<template>
<div class="wrapper wrapper-content">
<component :is="currentProjectMain"></component>
</div>
</template>
This is my router-view in index.html:
<router-view name="sidebar"></router-view>
And I have another one in index.html, the default one:
<router-view></router-view>
When I click on some item on Sidebar i emit event to the ProjectMain to switch out the component. So like this:
In Sidebar:
eventBus.$emit("currentProjectMainChanged", "appOverview");
or
eventBus.$emit("currentProjectMainChanged", "appSettings");
And than in ProjectMain:
eventBus.$on("currentProjectMainChanged", function(data) {
if(data === "appOverview") {
self.currentProjectMain = CurrentProjectAppOverview;
}else if(data === "appSettings") {
self.currentProjectMain = CurrentProjectSettings;
}
});
If I got to "/myapps/:id". It loads the sidebar and ProjectMain and I get a little animation of the sidebar and the ProjectMain with this bootstrap classes:
<div class="animated fadeInUp"> and both components got through the entire lifecycle.
By default appOverview is selected in sidebar and CurentProjectAppOverview.vue is loaded as a component in ProjectMain.
Than I click on appSettings in the sidebar and class is added to that item in the sidebar to mark it as selected and in the ProjectMain CurrentProjectSettings.vue is loaded as a component.
But then in the breadcrumbs I have a button to go to "/myapps/newversion/:id"
Here is the problem. When I click to go to "/myapps/newversion/:id" (router.push("/myapps/newversion/" + id);) the second item on the sidebar remains selected (appSettings) and in ProjectMain CurrentProjectSettings.vue remains loaded, and I don't get the bootstrap animation of the sidebar and ProjectMain, and the components don't go through their lifecycle.
What I want here when I click the button to go to "/myapps/newversion/:id" is my bootstrap animation (<div class="animated fadeInUp">), I want the Sidebar and ProjectMain to go through their entire lifecycle. And I want the default item to be selected on the sidebar (so appOverview) and default component to be loaded in ProjectMain (so CurentProjectAppOverview.vue).
There are colored buttons for the each item in the sidebar. If I go to "/myapps/newversion/:id" from "/myapps/:id", I want to load the data from the server into CurrentProjectAppOverview.vue and if all data is filled I want the button on the sidebar to be green and if not it should be red.
So In short when moving between this two routes I want to be able to load data and fill the fields I want, and I want bootstrap animation and default views to be selected and loaded and they should go through their entire lifecycle. Now router just reuses them as they are.
So something like "ReloadComponent: true", or destroy and recreate component.
I could duplicate SidebarProject.vue and ProjectMain.vue and rename them and in each route load basically a copy but that would mean I have to write the same code in different .vue files.
Before there was an option to set YouComponent.route.canReuse to false, which would do what I want, I think, but it is removed in the newest version.
I was facing the same problem. I will quote a found answer, which is really simple and great.
The simplest solution is to add a :key attribute to :
<router-view :key="$route.fullPath"></router-view>
This is because Vue Router does not notice any change if the same component is being addressed. With the key, any change to the path will trigger a reload of the component with the new data.
Partially thanx to this: https://forum.vuejs.org/t/vue-router-reload-component/4429
I've come up with a solution that works for me:
First I added a new function to jQuery which is used to retrigger bootstrap animation when the component loads.
$.fn.redraw = function(){
return $(this).each(function(){
var redraw = this.offsetHeight;
});
};
In component:
export default{
created:function(){
this.onCreated();
},
watch: {
'$route' (to, from) {
//on route change re run: onCreated
this.onCreated();
//and trigger animations again
$("#breadcrumbsCurrentProject").find(".animated").removeClass("fadeIn").redraw().addClass("fadeIn");
}
}
}
I call the onCreated(); method when the component loads and when the route reloads or the ID of the same route changes but the component stays the same I just call the method again. This takes care of the new data.
As for re triggering bootstrap animations I use redraw(); function I add to jQuery right on the start of the app. and this re triggers the animations on URL change:
$("#breadcrumbsCurrentProject").find(".animated").removeClass("fadeIn").redraw().addClass("fadeIn");
It looks like you are using vue-router.
I don't have your code, but I can show you how I handled this. See named-views.
Here is my router-map from my bundle.js file:
const router = new VueRouter({
routes: [
{ path: '/',
components: {
default: dashboard,
altside: altSide,
toolbar: toolbar
},
},
{ path: '/create',
components: {
default: create,
altside: altSide,
toolbar: toolbar
},
},
{ path: '/event/:eventId',
name: 'eventDashboard',
components: {
default: eventDashboard,
altside: altSide,
toolbar: eventToolbar,
},
children: [
{ path: '/', name: 'event', component: event },
{ path: 'tickets', name: 'tickets', component: tickets},
{ path: 'edit', name: 'edit', component: edit },
{ path: 'attendees', name: 'attendees', component: attendees},
{ path: 'orders', name: 'orders', component: orders},
{ path: 'uploadImage', name: 'upload', component: upload},
{ path: 'orderDetail', name: 'orderDetail', component: orderDetail},
{ path: 'checkin', name: 'checkin', component: checkin},
],
}
]
})
I have named-views of "default", "altside" and "toolbar" I am assigning a component to the named view for each path.
The second half of this is in your parent component where you assign the name
<router-view name="toolbar"></router-View>
Here is my parent template:
<template>
<router-view class="view altside" name="altside"></router-view>
<router-view class="view toolbar" name="toolbar"></router-view>
<router-view class="view default"></router-view>
</template>
So, what I've done is I've told the parent template to look at the named-view of the router-view. And based upon the path, pull the component I've designated in the router-map.
For my '/' path toolbar == the toolbar component but in the '/create' path toolbar = eventToolbar component.
The default component is dynamic, which allows me to use child components without swapping out the toolbar or altside components.
This is what I came up with:
import ProjectMain from './templates/ProjectMain.vue';
import SidebarProject from './templates/SidebarProject.vue';
//now shallow copy the objects so the new object are treated as seperatete .vue files with: $.extend({}, OriginalObject);
//this is so I don't have to create basically the same .vue files but vue-router will reload those files because they are different
const ProjectMainA = $.extend({}, ProjectMain);
const ProjectMainB = $.extend({}, ProjectMain);
const ProjectMainC = $.extend({}, ProjectMain);
const SidebarProjectA = $.extend({}, SidebarProject);
const SidebarProjectB = $.extend({}, SidebarProject);
const SidebarProjectC = $.extend({}, SidebarProject);
const routes = [
{
path: "/myapps/newproject",
components: {
default: ProjectMainA,
"breadcrumbs": BreadcrumbsNewProject,
"sidebar": SidebarProjectA
}
},
{
path: "/myapps/:id",
components: {
default: ProjectMainB,
"breadcrumbs": BreadcrumbsCurrentProject,
"sidebar": SidebarProjectB
}
},
{
path: "/myapps/newversion/:id",
components: {
default: ProjectMainC,
"breadcrumbs": BreadcrumbsNewVersion,
"sidebar": SidebarProjectC
}
}
];
This basically tricks the vue-router into thinking he's loading different .vue components, but they are actually the same. So I get everything I want: reloading of the component, animation, life cycle, and I don't have to write multiple similar or the same components.
What do you think, I'm just not sure if this is the best practice.

Categories

Resources