Search code examples
angularangular-event-emitter

Pass values to parent component with eventemitter


How could i send the value of 'mytoki' from my modal component to its parent ?

I'm not sure if i should create another EventEmitter or a service. Any suggestions ?

@Component({
  selector: 'app-modal',
  templateUrl: './modal.component.html',
  styleUrls: ['./modal.component.css']
})
export class ModalComponent implements OnInit {

  @Output()
  toHide = new EventEmitter();

  private usrname;
  private pswd;
  private visible: string;
  private mytoki;

  constructor(private loginservice: LoginService) { }

  ngOnInit() {
  }

  connect(usrname, pswd) {
    this.loginservice.getUserLogin(this.usrname, this.pswd).subscribe(
      response => {
        this.mytoki = response.headers.get('Authorization');
        sessionStorage.setItem('token', this.mytoki);
        console.log('Connected');
      }, err => {
        // TODO
        // login errors
        // put token into nav component
      }, () => {
          this.visible = 'hide';
          this.toHide.emit(this.visible);
          this.usrname = '';
          this.pswd = '';
      }
    );
  }
}

Solution

  • Declare your @Output() myTokiDetails; on the modal component

    Then for example after you set your sessionStorage do this.myTokiDetails.emit(this.mytoki)this will broadcast up the event and assuming you used a selector to add this to the parent you would on this modals selector: <app-modal (myTokiDetails)="parentComponentFunction($event)"></app-modal>