Deleting cookies
delete() expires a single cookie. deleteAll() expires every cookie the page can see, using the same options for each one.
import { ChangeDetectionStrategy, Component, inject, signal, WritableSignal } from '@angular/core';import { CookieService } from 'ngx-cookie-service';
@Component({ selector: 'delete-example', templateUrl: './delete-example.component.html', changeDetection: ChangeDetectionStrategy.OnPush,})export class DeleteExampleComponent { private readonly cookieService: CookieService = inject(CookieService);
protected readonly cookies: WritableSignal<Record<string, string>> = signal(this.cookieService.getAll());
protected addSamples(): void { this.cookieService.set('docs-cart', '3 items', { path: '/' }); this.cookieService.set('docs-language', 'en', { path: '/' }); this.cookieService.set('docs-consent', 'analytics', { path: '/' }); this.refresh(); }
protected delete(name: string): void { // path must match the path the cookie was set with. this.cookieService.delete(name, { path: '/' }); this.refresh(); }
protected deleteAll(): void { this.cookieService.deleteAll({ path: '/' }); this.refresh(); }
protected names(): string[] { return Object.keys(this.cookies()); }
private refresh(): void { this.cookies.set(this.cookieService.getAll()); }}<div class="docs-actions"> <button type="button" class="primary" (click)="addSamples()">Add sample cookies</button> <button type="button" (click)="deleteAll()" [disabled]="!names().length">deleteAll({{ '{' }} path: '/' {{ '}' }})</button></div>
@if (names().length) { <ul class="docs-list" aria-live="polite"> @for (name of names(); track name) { <li> <code>{{ name }}={{ cookies()[name] }}</code> <button type="button" (click)="delete(name)" [attr.aria-label]="'Delete cookie ' + name">delete()</button> </li> } </ul>} @else { <p class="docs-muted" aria-live="polite">No cookies are visible from this page.</p>}- Both methods need the
path(anddomain) the cookie was set with. A cookie set withpath: '/'isn’t deleted bydelete(name)called on/docs/. deleteAll()can only delete cookies the page can see.HttpOnlycookies and cookies on other paths aren’t touched.- Pass
partitioned: trueto delete partitioned cookies.