📎 Webclip
Connect Angular Components with Events, Bindings, and Services
The article explains how to wire an Angular interface so a command entry component and a story view component can interact without being tightly coupled. It uses ngModel for two-way binding, a service to receive commands, and an EventEmitter so another component can subscribe to new entries and update the story view.
Reading notes#
- The project starts with a text-based game UI called Doggo Quest that already has a story view and a player input area, but the two parts do not communicate yet.
- The article uses Angular two-way binding, events, event emitters, services, and subscriptions to connect the interface.
- A service is added to link the command entry component to the main story display.
- Services are described as classes that provide functionality to other parts of the application and can be injected automatically into component constructors.
- The service is generated with Angular CLI using
ng g s <name-of-service>. - The service is expanded with an
EventEmitterand ahandlePlayerInputmethod. - An
EventEmittercan emit events that other code subscribes to, and it can have no subscribers or many subscribers. - The command entry component receives the story service through dependency injection.
- The component’s
submitCommandmethod reads the command field and passes the value to the service. - After sending the command, the component clears the
Commandfield. - The template uses
(click)to callsubmitCommandwhen the button is clicked. - The template also uses
keyup.enterso pressing Enter triggers the same method. - In Angular templates, parentheses indicate events and brackets indicate binding.
[(ngModel)]="Command"is presented as a combination of property binding and event binding for two-way binding.- With two-way binding, user input updates the component field, and clearing the field in code updates the input box through change detection.
- The story view component also receives the story service through dependency injection.
- Instead of calling methods on the service, it subscribes to the
EntryAddedEventEmitter. - The story view component implements
OnInitandOnDestroyso it can subscribe and unsubscribe inngOnInitandngOnDestroy. - The subscription is stored so it can be released later.
- Unsubscribing is important to avoid errors and poor performance from dead components.
- When the
EntryAddedevent fires, the new entry is added to the story array and appears in the user interface through Angular binding and change detection. - The result is a flexible connection between components, with the user’s text appearing in the story view along with a default response.
