How to entirely delete a Component in Angular

avatar
Borislav Hadzhiev

Last updated: Apr 4, 2024
3 min

banner

# How to entirely delete a Component in Angular

Deleting a component is not supported with the Angular CLI, so you have to do it manually.

To delete an Angular component:

  1. Delete the component folder and its contents.

delete the component folder

In VS Code, you can right-click on the folder and select Delete or simply left-click the folder and press the Del key on your keyboard.

right click delete folder

  1. Open your src/app/app.module.ts file or the module in which you imported the component.

open app module ts file

  1. Remove the import statement of the component.

remove component import and declaration

  1. Remove the component from the declarations array in your @NgModule decorator.

  2. Here is what my src/app/app.module.ts file looks after I've deleted the import statement and the declarations entry.

after deleting component

  1. Search for references of the component in your code editor and delete them.

I've written a detailed guide on how to search all files in Visual Studio Code.

  1. Press:
  • Ctrl + Shift + F (Windows and Linux).
  • Cmd + Shift + F (macOS).
  1. Type the name of your component into the Search field.

search for references of the component

  1. If you find any import statements and references to the deleted component, make sure to remove them.

  2. If you get an error, restart your code editor and your server.

# Using the --dry-run option when issuing the ng generate command

Use the --dry-run option if you need to test the output of the ng generate command when creating a component.

The option enables you to view the output of the ng generate command without writing files to the disk.

shell
npx ng generate component example --dry-run

ng generate component with dry run option

The command lists the files that would get created and updated if you run the ng generate command without the --dry-run option.

As shown in the screenshot, generating a component updates your app.module.ts file because the command automatically imports the generated component and adds it to the declarations array.

Deleting a component via the Angular CLI is not supported, so you have to manually delete the component's folder and any import statements and references.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.