5

I have in my parent component, where I want to detect the emitted event.

child.component.ts

@Component({
    selector: 'child-component',
    templateUrl: './child.component.html',
    styleUrls: ['./child.component.scss']
})   
export class ChildComponent implements OnInit { 

    @Input() public state: String = 'CLOSED';

    @Output() public stateChanged: EventEmitter<String> = new EventEmitter<String>();

    this.stateChanged.emit(this.state);

}

parent.component.html

<router-outlet (stateChanged)="onStateChange($event)"><router-outlet>

parent.component.ts

onStateChange(event){
    console.log(event);
}

This doesn't work for me!

The compiled HTML code looks like:

<router-outlet></router-outlet>
<child-component>
    // all child component code
<child-component>

Is there any way to push (stateChanged)="onStateChange($event)" in <child-component> element?

Can anyone help, please?

PiyaModi
  • 213
  • 2
  • 9
  • 22

2 Answers2

10

<router-outlet></router-outlet> considered to be a placeholder with the purpose of adding routed components. It does not have support to any kind of bindings.

But there is an update to <router-outlet></router-outlet> with an event that allows getting added component : Source

<router-outlet (activate)="componentAdded($event)" (deactivate)="componentRemoved($event)"></router-outlet>

This helps to communicate with getters, setters and methods through componentAdded()

The preferred way is to use a shared service check these links to create shared services

1) Angular Doc

2) Create shared service angular

3) Example1 Example2

Keshan Nageswaran
  • 8,060
  • 3
  • 28
  • 45
  • 1
    there ARE bindings available on now. for example you can event bind to `(activate)="doAThing($event)"` which gives you the event anytime you the router loads a new component. `doAThing(e) {console.log(e.constructor.name)}` will give you the name of the component – sao Sep 07 '20 at 17:28
  • Thanks ! then i can just access any output i want from the `$event`, it is the actual component. event easier than using emitter – Adir Dayan Jul 22 '21 at 15:37
0

No you cannot have event Emitter on router-outlet.

I would suggest you to have your own componnet with input property and use the even on that

<list [list]="list" (onStateChanged)="stateChanged($event)"></list>

Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
  • Thanks, @Sajeetharan, for your answer. But I have updated my question. Can you please look at that? – PiyaModi Jul 17 '18 at 02:22