how to route on same component in angular?












0














Here i have multiple list of users. that users id is like(1,2,3,4,5....), click on button it shows first user details after that click on second user details button it shows second user details this is the functionality I want.



but when I click on second user details button, the url is changed but still the second user details does not show, it shows the first user details. So how do I route on same page using userid.



app-routing.module.ts



{ path: 'details/:userid', component : DetailsComponent}


details.component.html



<button mat-raised-button routerLink="details/{{userObj.userid}}">View<button>


details.component.ts



userObj: User = ;

constructor(private userService : UserService,private : ActivatedRoute){}

ngOnInit() {
const userid= +this.route.snapshot.paramMap.get('userid');
this.userService.getUsersDetails({'userid' : userid}).subscribe(
(data) => {
if(data.payload != undefined && data.payload != ''){
this.userObj= data.payload;
}
}
)
}









share|improve this question
























  • Could you please provide the full code of your component
    – mika
    Nov 23 '18 at 10:18










  • @mika i edit my code
    – user10694956
    Nov 23 '18 at 10:26












  • I think to get the updated userid you'll have to subscribe to route.params instead of using route.snapshot. Take a look at my answer and check to see if it helps.
    – SiddAjmera
    Nov 23 '18 at 11:01
















0














Here i have multiple list of users. that users id is like(1,2,3,4,5....), click on button it shows first user details after that click on second user details button it shows second user details this is the functionality I want.



but when I click on second user details button, the url is changed but still the second user details does not show, it shows the first user details. So how do I route on same page using userid.



app-routing.module.ts



{ path: 'details/:userid', component : DetailsComponent}


details.component.html



<button mat-raised-button routerLink="details/{{userObj.userid}}">View<button>


details.component.ts



userObj: User = ;

constructor(private userService : UserService,private : ActivatedRoute){}

ngOnInit() {
const userid= +this.route.snapshot.paramMap.get('userid');
this.userService.getUsersDetails({'userid' : userid}).subscribe(
(data) => {
if(data.payload != undefined && data.payload != ''){
this.userObj= data.payload;
}
}
)
}









share|improve this question
























  • Could you please provide the full code of your component
    – mika
    Nov 23 '18 at 10:18










  • @mika i edit my code
    – user10694956
    Nov 23 '18 at 10:26












  • I think to get the updated userid you'll have to subscribe to route.params instead of using route.snapshot. Take a look at my answer and check to see if it helps.
    – SiddAjmera
    Nov 23 '18 at 11:01














0












0








0







Here i have multiple list of users. that users id is like(1,2,3,4,5....), click on button it shows first user details after that click on second user details button it shows second user details this is the functionality I want.



but when I click on second user details button, the url is changed but still the second user details does not show, it shows the first user details. So how do I route on same page using userid.



app-routing.module.ts



{ path: 'details/:userid', component : DetailsComponent}


details.component.html



<button mat-raised-button routerLink="details/{{userObj.userid}}">View<button>


details.component.ts



userObj: User = ;

constructor(private userService : UserService,private : ActivatedRoute){}

ngOnInit() {
const userid= +this.route.snapshot.paramMap.get('userid');
this.userService.getUsersDetails({'userid' : userid}).subscribe(
(data) => {
if(data.payload != undefined && data.payload != ''){
this.userObj= data.payload;
}
}
)
}









share|improve this question















Here i have multiple list of users. that users id is like(1,2,3,4,5....), click on button it shows first user details after that click on second user details button it shows second user details this is the functionality I want.



but when I click on second user details button, the url is changed but still the second user details does not show, it shows the first user details. So how do I route on same page using userid.



app-routing.module.ts



{ path: 'details/:userid', component : DetailsComponent}


details.component.html



<button mat-raised-button routerLink="details/{{userObj.userid}}">View<button>


details.component.ts



userObj: User = ;

constructor(private userService : UserService,private : ActivatedRoute){}

ngOnInit() {
const userid= +this.route.snapshot.paramMap.get('userid');
this.userService.getUsersDetails({'userid' : userid}).subscribe(
(data) => {
if(data.payload != undefined && data.payload != ''){
this.userObj= data.payload;
}
}
)
}






angular






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 23 '18 at 10:40

























asked Nov 23 '18 at 10:14







user10694956



















  • Could you please provide the full code of your component
    – mika
    Nov 23 '18 at 10:18










  • @mika i edit my code
    – user10694956
    Nov 23 '18 at 10:26












  • I think to get the updated userid you'll have to subscribe to route.params instead of using route.snapshot. Take a look at my answer and check to see if it helps.
    – SiddAjmera
    Nov 23 '18 at 11:01


















  • Could you please provide the full code of your component
    – mika
    Nov 23 '18 at 10:18










  • @mika i edit my code
    – user10694956
    Nov 23 '18 at 10:26












  • I think to get the updated userid you'll have to subscribe to route.params instead of using route.snapshot. Take a look at my answer and check to see if it helps.
    – SiddAjmera
    Nov 23 '18 at 11:01
















Could you please provide the full code of your component
– mika
Nov 23 '18 at 10:18




Could you please provide the full code of your component
– mika
Nov 23 '18 at 10:18












@mika i edit my code
– user10694956
Nov 23 '18 at 10:26






@mika i edit my code
– user10694956
Nov 23 '18 at 10:26














I think to get the updated userid you'll have to subscribe to route.params instead of using route.snapshot. Take a look at my answer and check to see if it helps.
– SiddAjmera
Nov 23 '18 at 11:01




I think to get the updated userid you'll have to subscribe to route.params instead of using route.snapshot. Take a look at my answer and check to see if it helps.
– SiddAjmera
Nov 23 '18 at 11:01












5 Answers
5






active

oldest

votes


















0














I think the real issue here is that you're using snapshot.paramMap. If you use snapshot.paramMap, you won't get the updated state params in most of the cases.



To fix that, just subscribe to the route.params Observable. You'll get params on subscription, which you can use to get the userid. Just give this a try:



ngOnInit() {
this.route.params.subscribe(params => {
userid = params['userid'];
this.userService.getUsersDetails({
'userid': userid
}).subscribe(data => {
if (data.payload != undefined && data.payload != '') {
this.userObj = data.payload;
}
});
});
}





share|improve this answer





















  • can u help for this question stackoverflow.com/questions/53493549/…
    – user10694956
    Nov 27 '18 at 6:06



















0














I think string interpolation doesn't work when you dont bind to routerLink.



try this:



<button mat-raised-button [routerLink]="['details', userObj.userid]">View<button>






share|improve this answer





























    0














    you didn't sharing your code source or what you already tried but try this depends on what you described



    HTML



    <ng-container *ngFor="let userId in userObj">
    <button mat-raised-button routerLink="[ '/details', userId]">View<button>
    </ng-container>


    you have to loop on userObj array the problem is you not iterate on the array of userObj so when you execute this routerLink="details/{{userObj.userid}}" it takes the same user id on all buttons.






    share|improve this answer





























      0














      As I understood, this.userService.getUsersDetails() is not taking any user id as input and hence you are always getting the same data for any user id link.



      It should be like this.userService.getUsersDetails(userId)



      userId: string;
      constructor(private route: ActivatedRoute) {
      }

      ngOnInit() {
      this.route.paramMap
      .pipe(switchMap((params: ParamMap) => {
      const userId = params.get("userId");

      this.userService.getUsersDetails(userId).subscribe((data) => {
      if (data.payload != undefined && data.payload != '') {
      this.userObj = data.payload;
      }
      }, (errorResponse) => {
      });
      return of(params);
      }))
      .subscribe();
      }





      share|improve this answer





















      • i edit my code, using userid i get partiular user details but when id change userid that time userService not called
        – user10694956
        Nov 23 '18 at 10:42










      • I need to know about it a little bit. You are in details and you want to navigate to some other page? if not so, then you should handle it with another method, not on ngInit as it would be initialized on page load alone not on url change (since route didnt happen here)
        – Padmapriya Vishnuvardhan
        Nov 23 '18 at 10:49












      • i want to route on same page but userid is different
        – user10694956
        Nov 23 '18 at 15:36



















      0














      Please try with below code and amendment changes according in your component and service.



      Step 1: Router Link sample



      <a [routerLink]="['/details/1']">User Detial</a>


      Step 2: Service created with sample data.



      import { Injectable } from '@angular/core';
      import { Observable, of } from 'rxjs';

      @Injectable({
      providedIn: 'root'
      })
      export class ContactsService {

      contacts: Contact = ;
      constructor() {
      this.contacts.push({ id: 1, name: 'A' });
      this.contacts.push({ id: 2, name: 'B' });
      this.contacts.push({ id: 3, name: 'C' });
      this.contacts.push({ id: 4, name: 'D' });

      }
      getContact(id: number): Observable<Contact> {
      return of(this.contacts.find(x => x.id == id));
      }
      }

      export class Contact {
      name: string;
      id: number;
      }


      Step 3: Created HTML for displaying user id and name.



      <p>{{contact.id}}: {{contact.name}}</p>
      <input type="button" (click)="onNext()" value="Next">


      Step 4: User-detail component



      import { Component, OnInit } from '@angular/core';
      import { Router, ActivatedRoute } from '@angular/router';
      import { map } from 'rxjs/operators'
      import { ContactsService, Contact } from '../contacts.service';

      @Component({
      selector: 'app-user-detail',
      templateUrl: './user-detail.component.html',
      styleUrls: ['./user-detail.component.css']
      })
      export class UserDetailComponent implements OnInit {
      contact: Contact;
      userId: number;
      constructor(private route: ActivatedRoute, private router: Router, private contactsService: ContactsService) { }

      ngOnInit() {
      this.route.params
      .pipe(map(params => params['userid']))
      .subscribe((id) => {
      this.userId = id;
      this.contactsService
      .getContact(id)
      .subscribe(contact => this.contact = contact);
      });
      }

      onNext() {
      let id = parseInt(this.userId.toString()) + 1;
      this.router.navigate(['/details/' + id]);
      }
      }





      share|improve this answer





















        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53444711%2fhow-to-route-on-same-component-in-angular%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown
























        5 Answers
        5






        active

        oldest

        votes








        5 Answers
        5






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        0














        I think the real issue here is that you're using snapshot.paramMap. If you use snapshot.paramMap, you won't get the updated state params in most of the cases.



        To fix that, just subscribe to the route.params Observable. You'll get params on subscription, which you can use to get the userid. Just give this a try:



        ngOnInit() {
        this.route.params.subscribe(params => {
        userid = params['userid'];
        this.userService.getUsersDetails({
        'userid': userid
        }).subscribe(data => {
        if (data.payload != undefined && data.payload != '') {
        this.userObj = data.payload;
        }
        });
        });
        }





        share|improve this answer





















        • can u help for this question stackoverflow.com/questions/53493549/…
          – user10694956
          Nov 27 '18 at 6:06
















        0














        I think the real issue here is that you're using snapshot.paramMap. If you use snapshot.paramMap, you won't get the updated state params in most of the cases.



        To fix that, just subscribe to the route.params Observable. You'll get params on subscription, which you can use to get the userid. Just give this a try:



        ngOnInit() {
        this.route.params.subscribe(params => {
        userid = params['userid'];
        this.userService.getUsersDetails({
        'userid': userid
        }).subscribe(data => {
        if (data.payload != undefined && data.payload != '') {
        this.userObj = data.payload;
        }
        });
        });
        }





        share|improve this answer





















        • can u help for this question stackoverflow.com/questions/53493549/…
          – user10694956
          Nov 27 '18 at 6:06














        0












        0








        0






        I think the real issue here is that you're using snapshot.paramMap. If you use snapshot.paramMap, you won't get the updated state params in most of the cases.



        To fix that, just subscribe to the route.params Observable. You'll get params on subscription, which you can use to get the userid. Just give this a try:



        ngOnInit() {
        this.route.params.subscribe(params => {
        userid = params['userid'];
        this.userService.getUsersDetails({
        'userid': userid
        }).subscribe(data => {
        if (data.payload != undefined && data.payload != '') {
        this.userObj = data.payload;
        }
        });
        });
        }





        share|improve this answer












        I think the real issue here is that you're using snapshot.paramMap. If you use snapshot.paramMap, you won't get the updated state params in most of the cases.



        To fix that, just subscribe to the route.params Observable. You'll get params on subscription, which you can use to get the userid. Just give this a try:



        ngOnInit() {
        this.route.params.subscribe(params => {
        userid = params['userid'];
        this.userService.getUsersDetails({
        'userid': userid
        }).subscribe(data => {
        if (data.payload != undefined && data.payload != '') {
        this.userObj = data.payload;
        }
        });
        });
        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 23 '18 at 11:00









        SiddAjmera

        13.1k31137




        13.1k31137












        • can u help for this question stackoverflow.com/questions/53493549/…
          – user10694956
          Nov 27 '18 at 6:06


















        • can u help for this question stackoverflow.com/questions/53493549/…
          – user10694956
          Nov 27 '18 at 6:06
















        can u help for this question stackoverflow.com/questions/53493549/…
        – user10694956
        Nov 27 '18 at 6:06




        can u help for this question stackoverflow.com/questions/53493549/…
        – user10694956
        Nov 27 '18 at 6:06













        0














        I think string interpolation doesn't work when you dont bind to routerLink.



        try this:



        <button mat-raised-button [routerLink]="['details', userObj.userid]">View<button>






        share|improve this answer


























          0














          I think string interpolation doesn't work when you dont bind to routerLink.



          try this:



          <button mat-raised-button [routerLink]="['details', userObj.userid]">View<button>






          share|improve this answer
























            0












            0








            0






            I think string interpolation doesn't work when you dont bind to routerLink.



            try this:



            <button mat-raised-button [routerLink]="['details', userObj.userid]">View<button>






            share|improve this answer












            I think string interpolation doesn't work when you dont bind to routerLink.



            try this:



            <button mat-raised-button [routerLink]="['details', userObj.userid]">View<button>







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 23 '18 at 10:29









            mika

            23714




            23714























                0














                you didn't sharing your code source or what you already tried but try this depends on what you described



                HTML



                <ng-container *ngFor="let userId in userObj">
                <button mat-raised-button routerLink="[ '/details', userId]">View<button>
                </ng-container>


                you have to loop on userObj array the problem is you not iterate on the array of userObj so when you execute this routerLink="details/{{userObj.userid}}" it takes the same user id on all buttons.






                share|improve this answer


























                  0














                  you didn't sharing your code source or what you already tried but try this depends on what you described



                  HTML



                  <ng-container *ngFor="let userId in userObj">
                  <button mat-raised-button routerLink="[ '/details', userId]">View<button>
                  </ng-container>


                  you have to loop on userObj array the problem is you not iterate on the array of userObj so when you execute this routerLink="details/{{userObj.userid}}" it takes the same user id on all buttons.






                  share|improve this answer
























                    0












                    0








                    0






                    you didn't sharing your code source or what you already tried but try this depends on what you described



                    HTML



                    <ng-container *ngFor="let userId in userObj">
                    <button mat-raised-button routerLink="[ '/details', userId]">View<button>
                    </ng-container>


                    you have to loop on userObj array the problem is you not iterate on the array of userObj so when you execute this routerLink="details/{{userObj.userid}}" it takes the same user id on all buttons.






                    share|improve this answer












                    you didn't sharing your code source or what you already tried but try this depends on what you described



                    HTML



                    <ng-container *ngFor="let userId in userObj">
                    <button mat-raised-button routerLink="[ '/details', userId]">View<button>
                    </ng-container>


                    you have to loop on userObj array the problem is you not iterate on the array of userObj so when you execute this routerLink="details/{{userObj.userid}}" it takes the same user id on all buttons.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 23 '18 at 10:32









                    Amir Fawzy

                    2188




                    2188























                        0














                        As I understood, this.userService.getUsersDetails() is not taking any user id as input and hence you are always getting the same data for any user id link.



                        It should be like this.userService.getUsersDetails(userId)



                        userId: string;
                        constructor(private route: ActivatedRoute) {
                        }

                        ngOnInit() {
                        this.route.paramMap
                        .pipe(switchMap((params: ParamMap) => {
                        const userId = params.get("userId");

                        this.userService.getUsersDetails(userId).subscribe((data) => {
                        if (data.payload != undefined && data.payload != '') {
                        this.userObj = data.payload;
                        }
                        }, (errorResponse) => {
                        });
                        return of(params);
                        }))
                        .subscribe();
                        }





                        share|improve this answer





















                        • i edit my code, using userid i get partiular user details but when id change userid that time userService not called
                          – user10694956
                          Nov 23 '18 at 10:42










                        • I need to know about it a little bit. You are in details and you want to navigate to some other page? if not so, then you should handle it with another method, not on ngInit as it would be initialized on page load alone not on url change (since route didnt happen here)
                          – Padmapriya Vishnuvardhan
                          Nov 23 '18 at 10:49












                        • i want to route on same page but userid is different
                          – user10694956
                          Nov 23 '18 at 15:36
















                        0














                        As I understood, this.userService.getUsersDetails() is not taking any user id as input and hence you are always getting the same data for any user id link.



                        It should be like this.userService.getUsersDetails(userId)



                        userId: string;
                        constructor(private route: ActivatedRoute) {
                        }

                        ngOnInit() {
                        this.route.paramMap
                        .pipe(switchMap((params: ParamMap) => {
                        const userId = params.get("userId");

                        this.userService.getUsersDetails(userId).subscribe((data) => {
                        if (data.payload != undefined && data.payload != '') {
                        this.userObj = data.payload;
                        }
                        }, (errorResponse) => {
                        });
                        return of(params);
                        }))
                        .subscribe();
                        }





                        share|improve this answer





















                        • i edit my code, using userid i get partiular user details but when id change userid that time userService not called
                          – user10694956
                          Nov 23 '18 at 10:42










                        • I need to know about it a little bit. You are in details and you want to navigate to some other page? if not so, then you should handle it with another method, not on ngInit as it would be initialized on page load alone not on url change (since route didnt happen here)
                          – Padmapriya Vishnuvardhan
                          Nov 23 '18 at 10:49












                        • i want to route on same page but userid is different
                          – user10694956
                          Nov 23 '18 at 15:36














                        0












                        0








                        0






                        As I understood, this.userService.getUsersDetails() is not taking any user id as input and hence you are always getting the same data for any user id link.



                        It should be like this.userService.getUsersDetails(userId)



                        userId: string;
                        constructor(private route: ActivatedRoute) {
                        }

                        ngOnInit() {
                        this.route.paramMap
                        .pipe(switchMap((params: ParamMap) => {
                        const userId = params.get("userId");

                        this.userService.getUsersDetails(userId).subscribe((data) => {
                        if (data.payload != undefined && data.payload != '') {
                        this.userObj = data.payload;
                        }
                        }, (errorResponse) => {
                        });
                        return of(params);
                        }))
                        .subscribe();
                        }





                        share|improve this answer












                        As I understood, this.userService.getUsersDetails() is not taking any user id as input and hence you are always getting the same data for any user id link.



                        It should be like this.userService.getUsersDetails(userId)



                        userId: string;
                        constructor(private route: ActivatedRoute) {
                        }

                        ngOnInit() {
                        this.route.paramMap
                        .pipe(switchMap((params: ParamMap) => {
                        const userId = params.get("userId");

                        this.userService.getUsersDetails(userId).subscribe((data) => {
                        if (data.payload != undefined && data.payload != '') {
                        this.userObj = data.payload;
                        }
                        }, (errorResponse) => {
                        });
                        return of(params);
                        }))
                        .subscribe();
                        }






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Nov 23 '18 at 10:34









                        Padmapriya Vishnuvardhan

                        772210




                        772210












                        • i edit my code, using userid i get partiular user details but when id change userid that time userService not called
                          – user10694956
                          Nov 23 '18 at 10:42










                        • I need to know about it a little bit. You are in details and you want to navigate to some other page? if not so, then you should handle it with another method, not on ngInit as it would be initialized on page load alone not on url change (since route didnt happen here)
                          – Padmapriya Vishnuvardhan
                          Nov 23 '18 at 10:49












                        • i want to route on same page but userid is different
                          – user10694956
                          Nov 23 '18 at 15:36


















                        • i edit my code, using userid i get partiular user details but when id change userid that time userService not called
                          – user10694956
                          Nov 23 '18 at 10:42










                        • I need to know about it a little bit. You are in details and you want to navigate to some other page? if not so, then you should handle it with another method, not on ngInit as it would be initialized on page load alone not on url change (since route didnt happen here)
                          – Padmapriya Vishnuvardhan
                          Nov 23 '18 at 10:49












                        • i want to route on same page but userid is different
                          – user10694956
                          Nov 23 '18 at 15:36
















                        i edit my code, using userid i get partiular user details but when id change userid that time userService not called
                        – user10694956
                        Nov 23 '18 at 10:42




                        i edit my code, using userid i get partiular user details but when id change userid that time userService not called
                        – user10694956
                        Nov 23 '18 at 10:42












                        I need to know about it a little bit. You are in details and you want to navigate to some other page? if not so, then you should handle it with another method, not on ngInit as it would be initialized on page load alone not on url change (since route didnt happen here)
                        – Padmapriya Vishnuvardhan
                        Nov 23 '18 at 10:49






                        I need to know about it a little bit. You are in details and you want to navigate to some other page? if not so, then you should handle it with another method, not on ngInit as it would be initialized on page load alone not on url change (since route didnt happen here)
                        – Padmapriya Vishnuvardhan
                        Nov 23 '18 at 10:49














                        i want to route on same page but userid is different
                        – user10694956
                        Nov 23 '18 at 15:36




                        i want to route on same page but userid is different
                        – user10694956
                        Nov 23 '18 at 15:36











                        0














                        Please try with below code and amendment changes according in your component and service.



                        Step 1: Router Link sample



                        <a [routerLink]="['/details/1']">User Detial</a>


                        Step 2: Service created with sample data.



                        import { Injectable } from '@angular/core';
                        import { Observable, of } from 'rxjs';

                        @Injectable({
                        providedIn: 'root'
                        })
                        export class ContactsService {

                        contacts: Contact = ;
                        constructor() {
                        this.contacts.push({ id: 1, name: 'A' });
                        this.contacts.push({ id: 2, name: 'B' });
                        this.contacts.push({ id: 3, name: 'C' });
                        this.contacts.push({ id: 4, name: 'D' });

                        }
                        getContact(id: number): Observable<Contact> {
                        return of(this.contacts.find(x => x.id == id));
                        }
                        }

                        export class Contact {
                        name: string;
                        id: number;
                        }


                        Step 3: Created HTML for displaying user id and name.



                        <p>{{contact.id}}: {{contact.name}}</p>
                        <input type="button" (click)="onNext()" value="Next">


                        Step 4: User-detail component



                        import { Component, OnInit } from '@angular/core';
                        import { Router, ActivatedRoute } from '@angular/router';
                        import { map } from 'rxjs/operators'
                        import { ContactsService, Contact } from '../contacts.service';

                        @Component({
                        selector: 'app-user-detail',
                        templateUrl: './user-detail.component.html',
                        styleUrls: ['./user-detail.component.css']
                        })
                        export class UserDetailComponent implements OnInit {
                        contact: Contact;
                        userId: number;
                        constructor(private route: ActivatedRoute, private router: Router, private contactsService: ContactsService) { }

                        ngOnInit() {
                        this.route.params
                        .pipe(map(params => params['userid']))
                        .subscribe((id) => {
                        this.userId = id;
                        this.contactsService
                        .getContact(id)
                        .subscribe(contact => this.contact = contact);
                        });
                        }

                        onNext() {
                        let id = parseInt(this.userId.toString()) + 1;
                        this.router.navigate(['/details/' + id]);
                        }
                        }





                        share|improve this answer


























                          0














                          Please try with below code and amendment changes according in your component and service.



                          Step 1: Router Link sample



                          <a [routerLink]="['/details/1']">User Detial</a>


                          Step 2: Service created with sample data.



                          import { Injectable } from '@angular/core';
                          import { Observable, of } from 'rxjs';

                          @Injectable({
                          providedIn: 'root'
                          })
                          export class ContactsService {

                          contacts: Contact = ;
                          constructor() {
                          this.contacts.push({ id: 1, name: 'A' });
                          this.contacts.push({ id: 2, name: 'B' });
                          this.contacts.push({ id: 3, name: 'C' });
                          this.contacts.push({ id: 4, name: 'D' });

                          }
                          getContact(id: number): Observable<Contact> {
                          return of(this.contacts.find(x => x.id == id));
                          }
                          }

                          export class Contact {
                          name: string;
                          id: number;
                          }


                          Step 3: Created HTML for displaying user id and name.



                          <p>{{contact.id}}: {{contact.name}}</p>
                          <input type="button" (click)="onNext()" value="Next">


                          Step 4: User-detail component



                          import { Component, OnInit } from '@angular/core';
                          import { Router, ActivatedRoute } from '@angular/router';
                          import { map } from 'rxjs/operators'
                          import { ContactsService, Contact } from '../contacts.service';

                          @Component({
                          selector: 'app-user-detail',
                          templateUrl: './user-detail.component.html',
                          styleUrls: ['./user-detail.component.css']
                          })
                          export class UserDetailComponent implements OnInit {
                          contact: Contact;
                          userId: number;
                          constructor(private route: ActivatedRoute, private router: Router, private contactsService: ContactsService) { }

                          ngOnInit() {
                          this.route.params
                          .pipe(map(params => params['userid']))
                          .subscribe((id) => {
                          this.userId = id;
                          this.contactsService
                          .getContact(id)
                          .subscribe(contact => this.contact = contact);
                          });
                          }

                          onNext() {
                          let id = parseInt(this.userId.toString()) + 1;
                          this.router.navigate(['/details/' + id]);
                          }
                          }





                          share|improve this answer
























                            0












                            0








                            0






                            Please try with below code and amendment changes according in your component and service.



                            Step 1: Router Link sample



                            <a [routerLink]="['/details/1']">User Detial</a>


                            Step 2: Service created with sample data.



                            import { Injectable } from '@angular/core';
                            import { Observable, of } from 'rxjs';

                            @Injectable({
                            providedIn: 'root'
                            })
                            export class ContactsService {

                            contacts: Contact = ;
                            constructor() {
                            this.contacts.push({ id: 1, name: 'A' });
                            this.contacts.push({ id: 2, name: 'B' });
                            this.contacts.push({ id: 3, name: 'C' });
                            this.contacts.push({ id: 4, name: 'D' });

                            }
                            getContact(id: number): Observable<Contact> {
                            return of(this.contacts.find(x => x.id == id));
                            }
                            }

                            export class Contact {
                            name: string;
                            id: number;
                            }


                            Step 3: Created HTML for displaying user id and name.



                            <p>{{contact.id}}: {{contact.name}}</p>
                            <input type="button" (click)="onNext()" value="Next">


                            Step 4: User-detail component



                            import { Component, OnInit } from '@angular/core';
                            import { Router, ActivatedRoute } from '@angular/router';
                            import { map } from 'rxjs/operators'
                            import { ContactsService, Contact } from '../contacts.service';

                            @Component({
                            selector: 'app-user-detail',
                            templateUrl: './user-detail.component.html',
                            styleUrls: ['./user-detail.component.css']
                            })
                            export class UserDetailComponent implements OnInit {
                            contact: Contact;
                            userId: number;
                            constructor(private route: ActivatedRoute, private router: Router, private contactsService: ContactsService) { }

                            ngOnInit() {
                            this.route.params
                            .pipe(map(params => params['userid']))
                            .subscribe((id) => {
                            this.userId = id;
                            this.contactsService
                            .getContact(id)
                            .subscribe(contact => this.contact = contact);
                            });
                            }

                            onNext() {
                            let id = parseInt(this.userId.toString()) + 1;
                            this.router.navigate(['/details/' + id]);
                            }
                            }





                            share|improve this answer












                            Please try with below code and amendment changes according in your component and service.



                            Step 1: Router Link sample



                            <a [routerLink]="['/details/1']">User Detial</a>


                            Step 2: Service created with sample data.



                            import { Injectable } from '@angular/core';
                            import { Observable, of } from 'rxjs';

                            @Injectable({
                            providedIn: 'root'
                            })
                            export class ContactsService {

                            contacts: Contact = ;
                            constructor() {
                            this.contacts.push({ id: 1, name: 'A' });
                            this.contacts.push({ id: 2, name: 'B' });
                            this.contacts.push({ id: 3, name: 'C' });
                            this.contacts.push({ id: 4, name: 'D' });

                            }
                            getContact(id: number): Observable<Contact> {
                            return of(this.contacts.find(x => x.id == id));
                            }
                            }

                            export class Contact {
                            name: string;
                            id: number;
                            }


                            Step 3: Created HTML for displaying user id and name.



                            <p>{{contact.id}}: {{contact.name}}</p>
                            <input type="button" (click)="onNext()" value="Next">


                            Step 4: User-detail component



                            import { Component, OnInit } from '@angular/core';
                            import { Router, ActivatedRoute } from '@angular/router';
                            import { map } from 'rxjs/operators'
                            import { ContactsService, Contact } from '../contacts.service';

                            @Component({
                            selector: 'app-user-detail',
                            templateUrl: './user-detail.component.html',
                            styleUrls: ['./user-detail.component.css']
                            })
                            export class UserDetailComponent implements OnInit {
                            contact: Contact;
                            userId: number;
                            constructor(private route: ActivatedRoute, private router: Router, private contactsService: ContactsService) { }

                            ngOnInit() {
                            this.route.params
                            .pipe(map(params => params['userid']))
                            .subscribe((id) => {
                            this.userId = id;
                            this.contactsService
                            .getContact(id)
                            .subscribe(contact => this.contact = contact);
                            });
                            }

                            onNext() {
                            let id = parseInt(this.userId.toString()) + 1;
                            this.router.navigate(['/details/' + id]);
                            }
                            }






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 23 '18 at 12:11









                            Sanjay Katiyar

                            38518




                            38518






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.





                                Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                Please pay close attention to the following guidance:


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53444711%2fhow-to-route-on-same-component-in-angular%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Catalogne

                                Violoncelliste

                                Héron pourpré