Contents
In Angular, there is no ng-controller
directive. The concept of controllers was used in AngularJS, the predecessor of Angular. In the Angular, ng-controllers have been replaced by components.
In Angular, components are the building blocks of your application. They encapsulate the view (HTML), logic, and data associated with a particular part of your application’s user interface.
Here’s how you can create and use components in Angular for Angular ng-controller:
Create a Component
You can generate a new component using the Angular CLI (Command Line Interface) by running the following command:
ng generate component my-component
This will generate a new component with a TypeScript file, an HTML template, a CSS file, and other necessary files.
Define the Component
Open the TypeScript file (e.g., my-component.component.ts
) generated for your component. In this file, you define the component class, properties, methods, and any necessary logic.
import { Component } from '@angular/core';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent {
// Define properties and methods here
}
Create the Component’s Template
In the HTML template file (e.g., my-component.component.html
), you define the component’s view. This is where you structure and layout the content that the component will display.
<div>
<h1>Welcome to My Component</h1>
<!-- Add your HTML content here -->
</div>
Use the Component
To use the component in your application, you can include it in another template using its selector. For example, in the app.component.html
file:
<app-my-component></app-my-component>
This will render your MyComponent
within the AppComponent
.
Run Your Application
Start your Angular development server to see the component in action
ng serve
You can access your application at http://localhost:4200
In summary, in Angular ng-controller, you create components to encapsulate and manage specific parts of your application’s user interface. These components replace the concept of controllers and provide a more structured and modular approach to building web applications.