Skip to content

Add a form management feature to a signal store #48

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,7 @@ export const appRoutes: Route[] = [
FlightCardComponent
],
selector: 'demo-flight-search-redux-connector',
templateUrl: './flight-search.component.html',
templateUrl: './flight-form-search.component.html',
})
export class FlightSearchReducConnectorComponent {
private store = injectFlightStore();
Expand Down
1 change: 1 addition & 0 deletions apps/demo/src/app/app.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
<mat-nav-list>
<a mat-list-item routerLink="/todo">DevTools</a>
<a mat-list-item routerLink="/flight-search">withRedux</a>
<a mat-list-item routerLink="/flight-form-search">withForm</a>
<a mat-list-item routerLink="/flight-search-data-service-simple">withDataService (Simple)</a>
<a mat-list-item routerLink="/flight-search-data-service-dynamic">withDataService (Dynamic)</a>
<a mat-list-item routerLink="/flight-search-redux-connector">Redux Connector</a>
Expand Down
4 changes: 2 additions & 2 deletions apps/demo/src/app/app.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { RouterLink, RouterOutlet } from '@angular/router';
import { SidebarComponent } from "./core/sidebar/sidebar.component";
import { CommonModule } from '@angular/common';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatListItem, MatListModule } from '@angular/material/list';
import { MatListModule } from '@angular/material/list';

@Component({
selector: 'demo-root',
Expand All @@ -25,7 +25,7 @@ import { MatListItem, MatListModule } from '@angular/material/list';
RouterOutlet,
SidebarComponent,
CommonModule,
MatToolbarModule,
MatToolbarModule
]
})
export class AppComponent {
Expand Down
5 changes: 2 additions & 3 deletions apps/demo/src/app/app.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,9 @@ export const appConfig: ApplicationConfig = {
providers: [
provideClientHydration(),
provideRouter(appRoutes,
withComponentInputBinding()),
withComponentInputBinding()),
provideAnimations(),
provideHttpClient(),
importProvidersFrom(LayoutModule),

importProvidersFrom(LayoutModule)
],
};
27 changes: 2 additions & 25 deletions apps/demo/src/app/app.routes.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,8 @@
import { Route } from '@angular/router';
import { TodoComponent } from './todo/todo.component';
import { FlightSearchComponent } from './flight-search/flight-search.component';
import { FlightSearchSimpleComponent } from './flight-search-data-service-simple/flight-search-simple.component';
import { FlightEditSimpleComponent } from './flight-search-data-service-simple/flight-edit-simple.component';
import { FlightSearchDynamicComponent } from './flight-search-data-service-dynamic/flight-search.component';
import { FlightEditDynamicComponent } from './flight-search-data-service-dynamic/flight-edit.component';
import { TodoStorageSyncComponent } from './todo-storage-sync/todo-storage-sync.component';
import { FlightSearchReducConnectorComponent } from './flight-search-redux-connector/flight-search.component';
import { provideFlightStore } from './flight-search-redux-connector/+state/redux';

export const appRoutes: Route[] = [
{ path: 'todo', component: TodoComponent },
{ path: 'flight-search', component: FlightSearchComponent },
{
path: 'flight-search-data-service-simple',
component: FlightSearchSimpleComponent,
},
{ path: 'flight-edit-simple/:id', component: FlightEditSimpleComponent },
{
path: 'flight-search-data-service-dynamic',
component: FlightSearchDynamicComponent,
},
{ path: 'flight-edit-dynamic/:id', component: FlightEditDynamicComponent },
{ path: 'todo-storage-sync', component: TodoStorageSyncComponent },
{
path: 'flight-search-redux-connector',
providers: [provideFlightStore()],
component: FlightSearchReducConnectorComponent
path: '',
loadChildren: () => import('./lazy-routes').then((m) => m.lazyRoutes),
},
];
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<div [formGroup]="flightSearchForm">

<mat-form-field>
<mat-label>From</mat-label>
<input matInput formControlName="from">
</mat-form-field>
<mat-form-field>
<mat-label>To</mat-label>
<input matInput formControlName="to">
</mat-form-field>

<mat-form-field>
<mat-label>Dates</mat-label>
<mat-date-range-input [rangePicker]="picker">
<input matStartDate formControlName="start" placeholder="Start date">
<input matEndDate formControlName="end" placeholder="End date">
</mat-date-range-input>
<mat-datepicker-toggle matIconSuffix [for]="picker"></mat-datepicker-toggle>
<mat-date-range-picker #picker></mat-date-range-picker>
</mat-form-field>

<mat-form-field>
<mat-label>Period</mat-label>
<mat-select formControlName="period">
<mat-option>None</mat-option>
<mat-option value="7_days">Next 7 days</mat-option>
<mat-option value="14_days">Next 14 days</mat-option>
<mat-option value="custom">Custom</mat-option>
</mat-select>
</mat-form-field>
</div>

<mat-table [dataSource]="flightStore.flights()">
<!-- From Column -->
<ng-container matColumnDef="from">
<mat-header-cell *matHeaderCellDef>From</mat-header-cell>
<mat-cell *matCellDef="let element">{{ element.from }}</mat-cell>
</ng-container>

<!-- To Column -->
<ng-container matColumnDef="to">
<mat-header-cell *matHeaderCellDef>To</mat-header-cell>
<mat-cell *matCellDef="let element">{{ element.to }}</mat-cell>
</ng-container>

<!-- Date Column -->
<ng-container matColumnDef="date">
<mat-header-cell mat-header-cell *matHeaderCellDef>Date</mat-header-cell>
<mat-cell mat-cell *matCellDef="let element">{{
element.date | date
}}</mat-cell>
</ng-container>

<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
</mat-table>
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { Component, inject, OnInit } from '@angular/core';
import { MatTableModule } from '@angular/material/table';
import { DatePipe } from '@angular/common';
import { FlightStore } from './flight-store';
import { MatInputModule } from '@angular/material/input';
import { FormBuilder, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatOption, provideNativeDateAdapter } from '@angular/material/core';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatSelect } from '@angular/material/select';

@Component({
selector: 'demo-flight-form-search',
templateUrl: 'flight-form-search.component.html',
standalone: true,
providers: [provideNativeDateAdapter()],
imports: [
MatTableModule,
DatePipe,
MatInputModule,
FormsModule,
MatButtonModule,
ReactiveFormsModule,
MatFormFieldModule,
MatDatepickerModule,
MatSelect,
MatOption
]
})
export class FlightFormSearchComponent implements OnInit {
formBuilder = inject(FormBuilder);
flightSearchForm = this.formBuilder.group({
to: '',
from: '',
start: '',
end: '',
period: ''
});

flightStore = inject(FlightStore);
displayedColumns: string[] = ['from', 'to', 'date'];

ngOnInit(): void {
this.flightStore.setFlightsSearchFormGroup(this.flightSearchForm, this.flightStore);
}
}
75 changes: 75 additions & 0 deletions apps/demo/src/app/flight-search-form/flight-store.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { patchState, signalStore, withComputed, withMethods, withState } from '@ngrx/signals';
import {
withDevtools,
withForm, ControlChange, FormState, Reset, SetValue
} from 'ngrx-toolkit';
import { computed, inject } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Flight } from './flight';

export const FlightStore = signalStore(
{ providedIn: 'root' },
withDevtools('flights'),
withState({ flights: [] as Flight[] }),
withForm('flightsSearch', 500),
withComputed(({ flightsSearchFormState }) => {
return {

// -------- FORM MANAGEMENT -------
flightsSearchFormComputedChanges: computed<ControlChange[]>(() => {
const formState: FormState = flightsSearchFormState();
const changes: ControlChange[] = [];

// updating start/end picker date on period selected
if (formState.controlsMarkedAsChanged.some((control) => control === 'period')) {
const period = formState.value.period;
if (!period) {
changes.push({ controlName: 'start', operation: new Reset() });
changes.push({ controlName: 'end', operation: new Reset() });
} else {
changes.push({
controlName: 'start',
operation: new SetValue(
period === '' ? '' : new Date().toISOString()
)
});
changes.push({
controlName: 'end',
operation: new SetValue(
period === '7_days' ? new Date(Date.now() + 86400000 * 7).toISOString() :
period === '14_days' ? new Date(Date.now() + 86400000 * 14).toISOString() : ''
)
});
}
}

// updating period on picker changed
if (formState.controlsMarkedAsChanged.some((control) => control === 'start' || control === 'end') &&
!!formState.value?.start &&
!!formState.value?.end
) {
changes.push({
controlName: 'period',
operation: new SetValue('custom') // TODO compute period from dates
});
}

return changes;
})
};
}),
withMethods((store, httpClient = inject(HttpClient)) => ({
handleFlightsSearchForm() {
httpClient.get<Flight[]>(
'https://demo.angulararchitects.io/api/flight',
{
params: new HttpParams()
.set('from', store.flightsSearchFormState().value?.from)
.set('to', store.flightsSearchFormState().value?.to)
.set('start', store.flightsSearchFormState().value?.start)
.set('end', store.flightsSearchFormState().value?.end),
}
).subscribe(flights => patchState(store, { flights: flights }))
}
})),
);
7 changes: 7 additions & 0 deletions apps/demo/src/app/flight-search-form/flight.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export interface Flight {
id: number;
from: string;
to: string;
delayed: boolean;
date: Date;
}
33 changes: 33 additions & 0 deletions apps/demo/src/app/lazy-routes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { Route } from '@angular/router';
import { TodoComponent } from './todo/todo.component';
import { FlightSearchComponent } from './flight-search/flight-search.component';
import { FlightSearchSimpleComponent } from './flight-search-data-service-simple/flight-search-simple.component';
import { FlightEditSimpleComponent } from './flight-search-data-service-simple/flight-edit-simple.component';
import { FlightSearchDynamicComponent } from './flight-search-data-service-dynamic/flight-search.component';
import { FlightEditDynamicComponent } from './flight-search-data-service-dynamic/flight-edit.component';
import { TodoStorageSyncComponent } from './todo-storage-sync/todo-storage-sync.component';
import { provideFlightStore } from './flight-search-redux-connector/+state/redux';
import { FlightSearchReducConnectorComponent } from './flight-search-redux-connector/flight-search.component';
import { FlightFormSearchComponent } from './flight-search-form/flight-form-search.component';

export const lazyRoutes: Route[] = [
{ path: 'todo', component: TodoComponent },
{ path: 'flight-search', component: FlightSearchComponent },
{ path: 'flight-form-search', component: FlightFormSearchComponent },
{
path: 'flight-search-data-service-simple',
component: FlightSearchSimpleComponent,
},
{ path: 'flight-edit-simple/:id', component: FlightEditSimpleComponent },
{
path: 'flight-search-data-service-dynamic',
component: FlightSearchDynamicComponent,
},
{ path: 'flight-edit-dynamic/:id', component: FlightEditDynamicComponent },
{ path: 'todo-storage-sync', component: TodoStorageSyncComponent },
{
path: 'flight-search-redux-connector',
providers: [provideFlightStore()],
component: FlightSearchReducConnectorComponent,
}
];
2 changes: 1 addition & 1 deletion libs/ngrx-toolkit/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -381,7 +381,7 @@ export const appRoutes: Route[] = [
FlightCardComponent
],
selector: 'demo-flight-search-redux-connector',
templateUrl: './flight-search.component.html',
templateUrl: './flight-form-search.component.html',
})
export class FlightSearchReducConnectorComponent {
private store = injectFlightStore();
Expand Down
3 changes: 2 additions & 1 deletion libs/ngrx-toolkit/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
"peerDependencies": {
"@angular/common": "^17.0.0",
"@angular/core": "^17.0.0",
"@ngrx/signals": "^17.0.0"
"@ngrx/signals": "^17.0.0",
"@angular/forms": "^17.0.0"
},
"dependencies": {
"tslib": "^2.3.0"
Expand Down
2 changes: 2 additions & 0 deletions libs/ngrx-toolkit/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ export * from './lib/with-redux';
export * from './lib/with-call-state';
export * from './lib/with-undo-redo';
export * from './lib/with-data-service';
export * from './lib/with-form';
export { withStorageSync, SyncConfig } from './lib/with-storage-sync';
export * from './lib/redux-connector';
export * from './lib/redux-connector/rxjs-interop';

Loading