Utilizing input variables for data input via HTML is a common practice, but I prefer utilizing a shared service as the most organized method. Services serve as singleton classes where global data can be stored and accessed through dependency injection.
To create a service specifically for a component, you can generate it using
ng g service file-path/service-name
. It is advisable to place the service in the same directory as your component.
Add your data and define default values or leave them undefined as needed.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class MyComponentService {
selectedId?: number;
startDate = '';
endDate = '';
}
Inject the service into the component where values need to be set, such as the 'Main Page' in this context. Adjust the values based on your specific requirements.
export class MainPageComponent {
constructor(private myCompService: MyComponentService) {}
setSelectedId(id: number) {
this.myCompService.selectedId = id;
}
setDates(startDate: string, endDate: string) {
this.myCompService.startDate = startDate;
this.myCompService.endDate = endDate;
}
}
Inject the service into the component that will utilize the values.
export class MyComponent {
constructor(public myCompService: MyComponentService) {
}
<input type="number" [value]="myCompService.selectedId" />
<input type="date" [value]="myCompService.startDate" />
<input type="date" [value]="myCompService.endDate" />
You can also create getters and setters to manipulate the data similarly to local variables.
export class MyComponent {
constructor(private myCompService: MyComponentService) {}
get selectedId() {
return this.myCompService.selectedId;
}
set selectedId(id: number | undefined) {
this.myCompService.selectedId = id;
}
get startDate() {
return this.myCompService.startDate;
}
set startDate(date: string) {
this.myCompService.startDate = date;
}
get endDate() {
return this.myCompService.endDate;
}
set endDate(date: string) {
this.myCompService.startDate = date;
}
}
<input type="number" [value]="selectedId" />
<input type="date" [value]="startDate" />
<input type="date" [value]="endDate" />