I am using Angular 5 in combination with SortableJs.
On a page I have listed multiple cards grouped.
HTML looks like
<div class="group" *ngFor="let group of groups" [sortablejs]="group.cards" [sortablejsOptions]="sortableOptions">
<div class="card" *ngFor="let card of group.cards">
<button routerLink="card/edit/{{card.id}}">Edit</button>
</div>
</div>
After I move a card from one group to another and I click on edit button it will redirect me to a page where I can edit the selected card.
When it redirects me to that page the constructor and ngOnInit are not executed.
After I click an element, those two execute.
Update: Plunker code: https://embed.plnkr.co/mCJGo60sxQLQohWRYC3O/
EDIT: To see the problem you need to move one button from one group to another then click the same button you moved. You will see that the binding are not done.
When routing, if only the params of your router link are changing, (In your case :card.id) Angular will not destroy and recreate your component.
Angular destroys and recreates component only if your original route changes.
Hence onInit is not being called.
If you need the card.id in your component, you can subscribe to the params like this:
constructor(route:ActivatedRoute) {
route.params.subscribe(val => {
console.log("Button ID: " + val.id);
});
}
Note that you need to import and inject ActivatedRoute in your card edit component.
Entire code for app-component:
//our root app component
import {Component, NgModule, VERSION, OnInit} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import { SortablejsModule, SortablejsOptions } from 'angular-sortablejs';
import { Routes, RouterModule, ActivatedRoute } from '@angular/router';
@Component({
selector: 'my-app',
template: `<router-outlet></router-outlet>`,
})
export class App {
}
@Component({
selector: 'my-cards',
template: `
<p> Try to move buttons </p>
<div class="group" *ngFor="let group of groups" [sortablejs]="group.cards" [sortablejsOptions]="sortableOptions">
<div class="card" *ngFor="let card of group.cards">
<button routerLink="card/edit/{{card.id}}">Edit {{card.id}}</button>
</div>
<hr />
</div>
`,
})
export class Cards {
groups = [
{
id: 1,
cards: [
{
id: 1,
},
{
id: 2,
},
{
id: 3,
}
]
},
{
id: 2,
cards: [
{
id: 4,
},
{
id: 5,
},
{
id: 6,
}
]
}
];
sortableOptions: SortablejsOptions = {
group: 'checks'
}
}
@Component({
selector: 'my-card-edit',
template: `
<p routerLink="">Go Home</p>
<p>{{content}}</p>
<input type="text" value="{{content}}">
`,
})
export class CardEdit implements OnInit {
content = "content here";
constructor(route: ActivatedRoute) {
route.params.subscribe(val => {
console.log("Button ID: " + val.id);
});
}
}
@NgModule({
imports: [
BrowserModule,
SortablejsModule.forRoot({
animation: 0,
}),
RouterModule.forRoot([
{path: '', component: Cards},
{path: 'card/edit/:id', component: CardEdit}
])
],
declarations: [ App, Cards, CardEdit ],
bootstrap: [ App ]
})
export class AppModule {}