Implementing Event Emitter for Component Communication
Discover how to use EventEmitter for efficient communication between Angular components through input and output bindings.
0 likes
42 views
Rule Content
{ "title": "Implementing Event Emitter for Component Communication", "description": "Discover how to use EventEmitter for efficient communication between Angular components through input and output bindings.", "category": "Angular Cursor Rules", "rules": [ { "id": "angular-event-emitter-naming", "description": "Ensure EventEmitter properties are named using past-participle verbs to clearly indicate the event's occurrence.", "severity": "warning", "pattern": "@Output\\(\\)\\s+(\\w+):\\s+EventEmitter<.*>\\s*=\\s*new\\s+EventEmitter<.*>\\(\\);", "replacement": "@Output() $1: EventEmitter<...> = new EventEmitter<...>(); // Rename $1 to a past-participle verb, e.g., 'dataLoaded'" }, { "id": "angular-event-emitter-handler-naming", "description": "Prefix EventEmitter handler methods with 'on' followed by the event name to maintain consistency.", "severity": "warning", "pattern": "function\\s+(\\w+)\\(\\$event\\)\\s*{", "replacement": "function on$1($event) { // Ensure $1 matches the corresponding EventEmitter property name" }, { "id": "angular-event-emitter-in-services", "description": "Avoid using EventEmitter in Angular services; use RxJS Subjects instead for event handling.", "severity": "error", "pattern": "EventEmitter<.*>\\s*=\\s*new\\s+EventEmitter<.*>\\(\\);", "replacement": "// Replace EventEmitter with Subject or BehaviorSubject as appropriate" }, { "id": "angular-output-decorator", "description": "Use the @Output decorator with EventEmitter to facilitate communication from child to parent components.", "severity": "error", "pattern": "EventEmitter<.*>\\s*=\\s*new\\s+EventEmitter<.*>\\(\\);", "replacement": "@Output() eventName: EventEmitter<...> = new EventEmitter<...>();" }, { "id": "angular-event-emitter-subscription", "description": "Unsubscribe from EventEmitter subscriptions in the ngOnDestroy lifecycle hook to prevent memory leaks.", "severity": "warning", "pattern": "this\\.eventName\\.subscribe\\(.*\\);", "replacement": "const subscription = this.eventName.subscribe(...);\n// In ngOnDestroy: subscription.unsubscribe();" } ] }