Video lecture
Watch on YouTube(opens in a new tab)Sub topic 2
Serving the App Locally with ng serve
This chapter assumes you have already created a project with ng new. It also assumes you know ES modules, classes, and basic TypeScript decorators.
Running the development server
From the project folder, start the development server:
ng serve --openThe CLI compiles the app in memory and serves it at http://localhost:4200. When you save a file, it rebuilds and reloads the browser. You can choose another port with --port 4300. ng serve is for development only. To produce deployable files, run ng build, which writes an optimized bundle to dist/.
How the app starts
The browser loads index.html, which contains the root selector <app-root>. Then src/main.ts runs:
// src/main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { App } from './app/app';
bootstrapApplication(App, appConfig)
.catch((err) => console.error(err));appConfig in app.config.ts lists application-wide providers, such as provideRouter(routes). Older CLI versions name the root class AppComponent and put it in app.component.ts.
Building your first component
Generate a component with ng generate component greeting, or write one by hand. Components are standalone by default, so you do not need an NgModule.
import { Component } from '@angular/core';
@Component({
selector: 'app-greeting',
template: `
<h2>Hello, {{ name }}!</h2>
<input [value]="name" (input)="onInput($event)" />
<button [disabled]="name === ''" (click)="name = ''">Clear</button>
`,
})
export class Greeting {
name = 'Angular';
onInput(event: Event) {
this.name = (event.target as HTMLInputElement).value;
}
}To render it, add Greeting to the root component's imports array and place <app-greeting /> in its template.
Templates, interpolation and binding
| Syntax | Name | Direction |
|---|---|---|
| `{{ expr }}` | Interpolation | Component to text |
| `[prop]="expr"` | Property binding | Component to DOM property |
| `(event)="handler()"` | Event binding | DOM to component |
Here are common errors:
- If you forget to add a child component to
imports, Angular reports "is not a known element". [value]binds to the DOM property, not the HTML attribute. Use[attr.aria-label]when you need to set an attribute.
Exercise
The template uses <app-greeting /> but the browser console says "'app-greeting' is not a known element". What is the most likely fix?
Show answer
Import the Greeting class in the parent component file and add it to that component's imports array in @Component.