How to Delete Component in Angular
We will introduce how we can delete a component in Angular.
Delete Component in Angular
When we are building a web application that contains multiple components, we may come across a situation in which we may have to delete a component for some reason.
It is quite easy to create a component in Angular using Angular CLI, but there is no option to delete a component using the Angular CLI, so we have to manually delete it.
Deleting a component is not easy, as it can crash our web application if all instances of our component are not removed correctly.
This tutorial goes through an example in which we will create a component using Angular CLI and then delete it step by step so it will be easier for you to understand and follow all the steps.
Let’s create a new application by using the following command.
# angular
ng new my-app
After creating our new application in Angular, we will go to our application directory using this command.
# angular
cd my-app
Now, let’s run our app to check if all dependencies are installed correctly.
# angular
ng serve --open
We will create a new component using the following command.
# angular
ng g c newcomponent
You can see that a new folder newcomponent
is created inside the App
folder that contains 3 files newcomponent.component.ts
, newcomponent.component.html
, and newcomponent.component.css
. Now, let’s discuss how we can delete this component.
Follow these steps to easily delete a component without any errors in our web application.
-
Delete the folder of the component
newcomponent
, including all the files inside it. -
If your component doesn’t have a separate folder, you may need to delete the files having named the same as your component. In my example, we will delete 3 files
newcomponent.component.ts
,newcomponent.component.html
, andnewcomponent.component.css
. -
Open
app.module.ts
and delete where your component is imported, as shown below.# angular import { NewComponent } from './newcomponent.component';
-
Now delete the component’s declaration inside
@NgModule
as shown below.# angular @NgModule({ imports: [ BrowserModule, FormsModule ], declarations: [ AppComponent, HelloComponent, NewComponent ], bootstrap: [ AppComponent ] })
After following these steps, we can start our web application using the following command.
# angular
ng build
ng serve
It will load our web application without any error. We can delete a component manually and correctly following these simple and easy steps.
Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.
LinkedIn