locked
How to pass table name from first component to second component on angular 7 when click button ? RRS feed

  • Question

  • User696604810 posted

    I have two components and i need to pass table name from first component to second when click button on first component

    first component.ts

     <button class="btn btn-success"   (click)="getReferenceDataForEmp()">ReferenceFile</button> 
     getReferenceDataForEmp() {
      console.log('Reference fire');  
      this.router.navigate(['References']); 
       }

    second component.ts

    ngOnInit() {
        console.log('welcome');
         this.apiservice.getReferenceDataForEmployee('Employees')
        .subscribe( data=>{
         this.RefListVal = data; //SUBSCRIBE HERE
         console.log(this.RefListVal);
    
         });
    on API service function getreferenceDataForEmployee
     getReferenceDataForEmployee(tablename : string):Observable<referencecolumns[]> {
                    return this.http.get<referencecolumns[]>('https://localhost:44326/api/Reference/'+ tablename);
                  }
    As you see above in first component i write table name by hand this will make big error if i have more coponents
    so that i need to pass table name as above Employees from first component.ts to second component .ts


    Wednesday, March 20, 2019 2:04 AM

All replies

  • User-893317190 posted

    Hi ahmedbarbary,

    Since you are using route , you could pass querystring or pathvariable through router service.

    Below is my test code.

    My component1.

    <p>
      comp1 works!
      <button (click)="clicktoComp2()"> go to comp2</button>
    </p>
    
    
    import { Component, OnInit } from '@angular/core';
    import { Router,NavigationExtras} from '@angular/router'
    @Component({
      selector: 'app-comp1',
      templateUrl: './comp1.component.html',
      styleUrls: ['./comp1.component.css']
    })
    export class Comp1Component implements OnInit {
    
      constructor(private router:Router) { }
    
      ngOnInit() {
      }
       clicktoComp2(){
        let navigationExtras: NavigationExtras = {  //set query string
          queryParams: { 'tablename': "get table name from query string" },
          
        };
        this.router.navigate(["comp2"],navigationExtras); //navigate with query string
      }
    }
    

    My component2.

    <p>
      comp2 works!
      <strong>{{tablename}}</strong>
    </p>
    
    
    
    import { Component, OnInit } from '@angular/core';
    import { Router,ActivatedRoute} from '@angular/router'
    @Component({
      selector: 'app-comp2',
      templateUrl: './comp2.component.html',
      styleUrls: ['./comp2.component.css']
    })
    export class Comp2Component implements OnInit {
       tablename:string
      constructor(
        private route:ActivatedRoute,
        private router:Router
      ) { }
    
      ngOnInit() {
               //get query string with queryParamMap
          this.tablename= this.route.snapshot.queryParamMap.get("tablename");
      }
    
    }

    My route configuration .

    const routes: Routes = [
       {path:"comp1",component:Comp1Component},
       {path:"comp2",component:Comp2Component}
    ];
    
    @NgModule({
      imports: [RouterModule.forRoot(routes)],
      exports: [RouterModule]
    })
    export class AppRoutingModule { }

    AppCompoent 

    <a routerLink="comp1" routerLinkActive="active">comp1</a><br>
    <a routerLink="comp2" >comp2</a>
    <router-outlet></router-outlet>

    The result.

    Another way is create a public service and store the data in the service and subscribe it in compoent2.

    https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service

    Maybe you could find other ways in the component-interaction section.

    Best regards,

    Ackerly Xu

    Wednesday, March 20, 2019 6:17 AM
  • User696604810 posted

    thank you for reply 

    this is actullay give me answer what i need  but i need 

    to use @input and @output to pass table name from component to component

    but i dont know how to use it

    can you tell me please ?

    Wednesday, March 20, 2019 12:08 PM
  • User-893317190 posted

    Hi ahmedbarbary,

    If you want to use output and input , I think you should use a parent compoent  as intermediary.

    Below is my code.

    Comp1

    export class Comp1Component implements OnInit {
    
      constructor(private router:Router) { }
    
      ngOnInit() {
      }
       
      @Output()
      myclick:EventEmitter<string> = new EventEmitter<string>()  // use the output decorator
    
      buttonClick(){
         this.myclick.emit("this is table name passed by output tablename")  // pass value through output propoerty
      }
    }



    <p>
    comp1 works!
    <!-- <button (click)="clicktoComp2()"> go to comp2</button> -->
    <button (click)="buttonClick()">pass to comp2</button>
    </p>

    Comp2

    export class Comp2Component implements OnInit {
      
       @Input() 
       tablenamebyparent:string  //use input property to receive output property
      constructor(
       
      ) { }
    
      ngOnInit() {
         
      
      }
    
    }

    <p>
    comp2 works!
     
    <strong>{{tablenamebyparent}}</strong>
    </p>

    ParentComoonent.

    @Component({
      selector: 'app-compparent',
      templateUrl: './compparent.component.html',
      styleUrls: ['./compparent.component.css']
    })
    export class CompparentComponent implements OnInit {
       tablename:string
      constructor() { }
    
      ngOnInit() {
      }
     passtablename(data){
       this.tablename =data; 
     }
    }

    <p>
     <app-comp1 (myclick)="passtablename($event)"></app-comp1>  receive output data
     <app-comp2  [tablenamebyparent]="tablename"></app-comp2>   inject the output data from comp1 into comp2's input property 
    </p>

    Appcompoent.

    <app-compparent></app-compparent>

    The result. Please omit the two links, it is from my last sample.

    Best regards,

    Ackerly Xu

    Thursday, March 21, 2019 1:33 AM