简体   繁体   中英

How to bind event from child to parent component in Angular 2+ in ngSwitch

My parent component calls the child component with a ngSwitch case:

<div *ngSwitchDefault>
   <app-child-comp (toggleHelp)="toggleHelp($event)"></app-child-comp>
</div>

And in the child component:

@Output() toggleHelp = new EventEmitter();
this.toggleHelp.emit(true);

And in the parent component:

toggleHelp() {
  console.log('event fired');
}

So far no success. If I call the component without ngSwitch , then it works fine. Any help would be appreciated.

This works fine:

Parent HTML :

<div [ngSwitch]="valuess">
  <div *ngSwitchCase="1">11111111111111111</div>
  <div *ngSwitchDefault>
    <app-child (toggleHelp)="toggleHelp($event)">

    </app-child>
  </div>
</div>
<a (click)="changeValue()">valuess</a>

Parent TS :

valuess = 1;
toggleHelp(evt) {
    console.log('event fired',evt);
}
changeValue(){
    this.valuess = 2;
}

Child HTML :

 <a (click)="toggleHelpCall()">toggleHelp</a>

Child TS :

export class ChildComponent implements OnInit {
    @Output() toggleHelp = new EventEmitter();
    constructor() { }

    ngOnInit() {
    }
    toggleHelpCall() {
        this.toggleHelp.emit(true);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM