You can create a service that can send notifications to other components that will process this command. A service might look like this:
import { Injectable } from "@angular/core"; import { Subject } from "rxjs/Subject"; @Injectable() export class DataSavingService { private dataSavingRequested = new Subject<void>(); public dataSavingRequested$ = this.dataSavingRequested.asObservable(); public requestDataSaving(): void { this.dataSavingRequested.next(); } }
... and must be registered in the providers section of the module. Note. If the data should be transmitted in the notification, you can declare a non-parametric parameter type for the dataSavingRequested Subject theme (for example, string ).
The service will be inserted into the component with the textarea element and called in the Enter keypress event handler:
import { DataSavingService } from "./services/data-saving.service"; ... @Component({ template: ` <textarea (keypress.enter)="handleEnterKeyPress($event)" ...></textarea> ` }) export class ComponentWithTextarea { constructor(private dataSavingService: DataSavingService, ...) { ... } public handleEnterKeyPress(event: KeyboardEvent): void { event.preventDefault();
The component with the "Save" button will subscribe to the dataSavingRequested$ service notification and save the data upon notification:
import { Component, OnDestroy, ... } from "@angular/core"; import { Subscription } from "rxjs/Subscription"; import { DataSavingService } from "../services/data-saving.service"; ... @Component({ ... }) export class ComponentWithSaveButton implements OnDestroy { private subscription: Subscription; constructor(private dataSavingService: DataSavingService, ...) { this.subscription = this.dataSavingService.dataSavingRequested$.subscribe(() => { this.saveData(); }); } public ngOnDestroy(): void { this.subscription.unsubscribe(); } private saveData(): void {
The above code assumes that the save should be performed in the component using the "Save" button. An alternative would be to move this logic to a service that could set the saveData method, which could be called by components. However, the service will need to collect data for storage. It can be obtained using the Subject / Observable mechanism or directly passed by components as a saveData parameter or by calling another service method.
ConnorsFan
source share