Angular pass callback function to child component as @Input similar to AngularJS way

后端 未结 10 1632
庸人自扰
庸人自扰 2020-11-27 10:22

AngularJS has the & parameters where you could pass a callback to a directive (e.g AngularJS way of callbacks. Is it possible to pass a callback as an @Input

10条回答
  •  伪装坚强ぢ
    2020-11-27 10:33

    As an example, I am using a login modal window, where the modal window is the parent, the login form is the child and the login button calls back to the modal parent's close function.

    The parent modal contains the function to close the modal. This parent passes the close function to the login child component.

    import { Component} from '@angular/core';
    import { LoginFormComponent } from './login-form.component'
    
    @Component({
      selector: 'my-modal',
      template: `
          
        `
    })
    export class ParentModalComponent {
      modal: {...};
    
      onClose() {
        this.modal.close();
      }
    }
    

    After the child login component submits the login form, it closes the parent modal using the parent's callback function

    import { Component, EventEmitter, Output } from '@angular/core';
    
    @Component({
      selector: 'login-form',
      template: `
    ` }) export class ChildLoginComponent { @Output() onClose = new EventEmitter(); submitted = false; onSubmit() { this.onClose.emit(); this.submitted = true; } }

提交回复
热议问题