get value from another component angular 4

后端 未结 3 1025
孤城傲影
孤城傲影 2020-12-25 08:18

I have two separate components; a header component containing a select search box, stats component that shows the results depending on the value of the select box, I was won

相关标签:
3条回答
  • 2020-12-25 09:05

    Use Shared Services:

    Service:

    @Injectable()
    export class MyService {
        myMethod$: Observable<any>;
        private myMethodSubject = new Subject<any>();
    
        constructor() {
            this.myMethod$ = this.myMethodSubject.asObservable();
        }
    
        myMethod(data) {
            console.log(data); // I have data! Let's return it so subscribers can use it!
            // we can do stuff with data if we want
            this.myMethodSubject.next(data);
        }
    }
    

    Component1 (sender):

    export class SomeComponent {
        public data: Array<any> = MyData;
    
        public constructor(private myService: MyService) {
            this.myService.myMethod(this.data);
        }
    }
    

    Component2 (receiver):

    export class SomeComponent2 {
        public data = {};
    
        public constructor(private myService: MyService) {
            this.myService.myMethod$.subscribe((data) => {
                    this.data = data; // And he have data here too!
                }
            );
        }
    }
    

    Check documentation!

    0 讨论(0)
  • The best way is to send the data to the component.

    Use the @Input property to send the data to the controller. Then implement ngOnChanges and execute the function to load the data.

    import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
    
    @Component({
        selector: 'second-component',    
    })
    
    @Injectable()
    export class SecondComponent implements OnChanges {
    
        @Input()
        selectValue: string;
    
        ngOnChanges(changes: SimpleChanges) {
               if (changes['selectValue']) {
                 //call your function to load the data
               }
        }
        
    }
    

    uses

    <second-component [selectValue]="bindYourValue"></second-component>
    
    0 讨论(0)
  • 2020-12-25 09:21

    I think that the best for your case would be to use service for communication between components.

    Check out example in Angular documentation: https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service

    0 讨论(0)
提交回复
热议问题