Default options
This demo’s CookieService was created with app-wide defaults. The first button passes no options, so every attribute comes from the defaults. The second overrides sameSite and expires, while path and secure still come from the defaults.
import { ChangeDetectionStrategy, Component, createEnvironmentInjector, DestroyRef, EnvironmentInjector, inject, signal, WritableSignal } from '@angular/core';import { CookieService, provideCookieOptions } from 'ngx-cookie-service';import { CookieInspectorComponent } from '../shared/cookie-inspector.component';
@Component({ selector: 'default-options-example', templateUrl: './default-options-example.component.html', imports: [CookieInspectorComponent], changeDetection: ChangeDetectionStrategy.OnPush,})export class DefaultOptionsExampleComponent { private readonly parentInjector: EnvironmentInjector = inject(EnvironmentInjector);
// In an app: providers: [provideCookieOptions({ ... })] in app.config.ts, then inject(CookieService) as usual. private readonly cookieService: CookieService = this.createService();
protected readonly cookieName: WritableSignal<string> = signal('docs-defaults'); protected readonly refresh: WritableSignal<number> = signal(0);
protected setWithDefaults(): void { // No options here: path, expires and sameSite all come from provideCookieOptions(). this.cookieService.set('docs-defaults', 'yes'); this.show('docs-defaults'); }
protected setWithOverride(): void { // Options passed to the call win over the defaults; the rest still apply. this.cookieService.set('docs-override', 'yes', { sameSite: 'Lax', expires: 30 }); this.show('docs-override'); }
private show(name: string): void { this.cookieName.set(name); this.refresh.update((r) => r + 1); }
private createService(): CookieService { const injector = createEnvironmentInjector( [CookieService, provideCookieOptions({ path: '/', expires: 1, sameSite: 'Strict', secure: true })], this.parentInjector ); inject(DestroyRef).onDestroy(() => injector.destroy()); return injector.get(CookieService); }}<pre class="docs-output">provideCookieOptions({{ '{' }} path: '/', expires: 1, sameSite: 'Strict', secure: true {{ '}' }})</pre><div class="docs-actions"> <button type="button" class="primary" (click)="setWithDefaults()">set('docs-defaults', 'yes')</button> <button type="button" (click)="setWithOverride()">set('docs-override', 'yes', {{ '{' }} sameSite: 'Lax', expires: 30 {{ '}' }})</button></div>
<h4 class="docs-subheading"> Stored attributes of <code>{{ cookieName() }}</code></h4><docs-cookie-inspector [name]="cookieName()" [refresh]="refresh()" />See Default options for the rules.