How to access variables of one component in another component [Angular]

后端 未结 2 1765
渐次进展
渐次进展 2021-01-29 07:59

I\'m new to Angular. I\'m trying a simple thing today. I\'ve gone through many answers but not able implement them correctly. I want to access some variables of filter-pan

2条回答
  •  我在风中等你
    2021-01-29 08:26

    You can create a service to share the data between components,

    A new service called, filter-panel.service.ts file with setter() and getter() method,

    import { Injectable } from '@angular/core';
    
    @Injectable()
    export class FilterPanelService {
    
      filterdata: any[];
      constructor() { }
    
       get data(): any{
        return this.filterdata;
      }
    
      set data(val: any){
        this.filterdata = val;
        console.log(this.filterdata);
      }
    
    }
    

    In filter-panel.component.ts set the value like,

    export class FilterPanelComponent implements OnInit {
    
        public activeFilters: string[];
        public text: string="hello world";
    
        constructor(public filterPanelService:FilterPanelService) {
    
            this.activeFilters = [
                'Provider: CMS',
                'Region: All',
                'Provider Group:All',
                'Provider: CMS',
                'Region: All',
                'Provider Group: All'
            ];
    
            this.filterPanelService.data = this.activeFilters;
        }
    
        ngOnInit() {}
    }
    

    And in filter-bar.component.ts get the value like,

    export class FilterBarComponent implements OnInit {
        @ViewChild('FilterPanelComponent', {static : false}) filterPanel: FilterPanelComponent;
    
    
        public values1: string[] = ['Philips'];
    
        public values2: string[];
    
    
        constructor(public filterPanelService: FilterPanelService) {
    
          //this.values2=this.filterPanel.activeFilters;  
        }
    
        ngOnInit() {
            //console.log(this.values2);
            console.log('value received ', this.filterPanelService.data);
        }
    }
    

    Working Stackblitz..

提交回复
热议问题