Search code examples
angularcomponentsoutputeventemitter

Is it safe to use ones of component without eventEmitter in the parent component?


I am using eventEmitter (from child) to inform parent about some events. I have more than one component, but... not all of them need to use the method call. Is it a way to inform the parent that ones of component should not emit if it is only static? Is it safe to use emit without any events ?

I have a parent where i am using 9x , but there are only 2 of them which are setting criterias for filters and navigate to another component.

All of has an Output() emitter which is used in html to emit an empty event. In the parent component i have methods with setting criterias and navigation which i use in as output.

This works fine, but i would like to know if it could make problems in the future or if it is unsafe idea. I will write an example code below.

child.component.ts

Output() emitter = new EventEmitter();

child.component.ts

    <button (click)="emitter.emit()"
        class="btn btn-primary"> example text
    </button>

parent.component.ts

    public onGetOnlineDevices() {
        this.deviceState.setCriteriaWithReset({ isOnline: true });
        this.navigate();
    }

parent.component.ts

            <div class="col-xl-6">
                <child-component
                (emitter)="onGetOnlineDevices($event)"
                ></child-component>
            </div>
            <div class="col-xl-6">
                <child-component></child-component>
            </div>
            <div class="col-xl-6">
                <child-component></child-component>
            </div>

Only first child-component will set criterias and navigate, but i am not sure if it safe to leave another components without any methods. Thanks for the answer.


Solution

  • It is safe as in they won't be consuming what the event emitter is emitting.

    What I think you need to do though is create separate components. Child component that emit should be one type of component, while child component that does not emit should be a different type of component as they seem to have different purposes. If they do have a lot in common, create a base class between them to share functionality.

    This would be the way to go to achieve clean code.