How to pass data from one component to other in angular 2

前端 未结 2 1217
逝去的感伤
逝去的感伤 2020-12-20 06:22

I have my login controller where i login and on success I get data to be displayed on home page. How do i pass this data to home component?

this is the function in l

2条回答
  •  佛祖请我去吃肉
    2020-12-20 06:29

    Yes, theres a way to do it,and you do this through the Output decorator and EventEmmiter class (both from angular/core). For example, in one of my projects I use select2 for Angular, wich tells me the actual selected value through the output "valueChanged", then I made a "event handler" wich will be executed everytime "valueChanged" event is executed. This event handler is also an output event itself, and will be executed just after valueChanged, and I do this to pass data to the parent component. You can repeat this approach all the times you need. Here is my code

    ts:

    import { Output, EventEmitter, Component, OnInit } from '@angular/core';
    
    @Component({
      selector: 'app-select2item',
      templateUrl: './select2item.component.html',
      styleUrls: ['./select2item.component.css']
    })
    export class Select2itemComponent implements OnInit {
    
        private select2options:S2options;
      private selected:string;
      @Output()//this is how you declare a custom "output event"
      selectedItem = new EventEmitter();
      constructor() { }
    
      ngOnInit() {
        this.select2options = {};
        this.select2options.ajax={
            url:"/item/ajax",
            dataType: 'json',
            data: (term)=>{ //console.log(term.term);
            return {sku:term.term}; 
          },
            delay:1000,
            processResults: (data)=>{
                console.log(data);
                return {
                    results:data.map((item)=>{
                        return {id:item.id, text:item.name};
                    })
                }
            }
        };
    
      }
    //and this is where you define your custom "output event"
      public currentItem(e:any){
        this.selected=e.value;
        this.selectedItem.emit(this.selected);
      }
    
    }
    

    html:

    
    

    take a look to this quick tutorial, it will help you (its made by Ionic team):

    Angular Outputs

提交回复
热议问题