Search code examples
angularangular-ng-if

Angular 2/4 click event in child show component in parent


I'm really struggling to get this working and have spent way to long on what appears to be a simple implementation.

I have a parent(quote-results) component with two child components:

<quote-table></quote-table>
<call-back-pop-up *ngIf="showCallBackPopUp"></call-back-pop-up>

I have a button with a click event in the child 'quote-table' component:

<button class="button-secondary" (click)="showCallbackToggle()">Request a callback</button>

And have a function for the click event in this child 'quote-form' component and an @Output():

@Output() showCallBackPopUp;

showCallbackToggle() {
  this.showCallBackPopUp = true;
}

I also have an @Input() in the parent(quote-results) component:

 @Input() showCallBack: boolean;

I would like the call-back-pop-up component to show on the click event triggered inside 'quote-table'

I have tried switching the @Input and @Output using a Boolean for this and emitter but have had not luck.

What am I doing wrong and how can I get this to work?


Solution

  • Your child component needs to emit it's output event and the parent needs to bind to it.

    this is how the child would emit the event:

    @Output() showCallBackPopUp = new EventEmitter();
    
    showCallbackToggle() {
      this.showCallBackPopUp.emit(true);
    }
    

    Outputs are always event emitters and they emit values via their emit method.

    then the parent binds to it in template like this:

    <quote-table (showCallBackPopUp)="showCallBackPopUp = true"></quote-table>
    

    and then you're done. the () syntax is stdard Angular event binding syntax, just like you bind to the click event that your button emits as part of the normal HTML5 api. If you give no arguments to @Output() then the event name will be the variable name (in this case "showCallBackPopUp"), but you could also do somehting like @Output('customEventName') which would change the event name to whatever string you put in. so your binding wold instead be (customEventName)="...do whatever.."

    You can also get the value that was emitted using the $event keyword in template like:

    <quote-table (showCallBackPopUp)="showCallBackPopUp = $event"></quote-table>
    

    if you wanted your child to be able to emit true or false and have your parent react accordingly.