Standalone apps and NgModules
bootstrapApplication(App, config)@NgModuleOptional now.{{ }} and [prop] send values to the template, (event) calls the class, and [( )] does both.inject(). Dependency injection finds it in the nearest injector, or in a parent up to the root.markForCheck() starts a check.count().bootstrapApplication(App, config)@NgModuleOptional now.@Component({...})template: '<h1>Hi</h1>'templateUrl: 'user.html'imports: [UserCard]{{ user.name }}[disabled]="busy"(input)="onType($event)" TrapInterpolation always turns the value into a string. Use [prop] for a boolean, a number or an object.
{{ d | date:'short' }}{{ p | currency:'USD' }}@Pipe({ name: 'truncate' })transform(value, limit)pure: falseCostly. Pure is the default.computed(() => ...)TrapA pure pipe misses items.push(), because the array reference stays the same. Assign a new array instead.
@if (ok) { } @else { }@for (u of users; track u.id) { }*ngIf*ngForDeprecated since 20, like ngSwitch.TrapA CSS rule that sets display overrides hidden and shows the element again.
host: { '(mouseenter)': 'on()' }* wraps the element in an ng-template. Render it with ViewContainerRef .<ng-content select="[title]" /><ng-template #tpl>*ngTemplateOutlet="tpl" <ng-container>TrapAngular always creates projected content, even when its slot sits in a false @if. Pass an ng-template instead.
id = input<string>()picked = output<string>()@Input() id@Output() picked[( )] on your own componentvalue = model(0)TrapChanging bound state in ngAfterViewInit throws Expression in development.
ngOnInit.ngOnChanges(changes) It gets the old and new values.ngOnDestroy()Clear timers and listeners, or use DestroyRef.@Injectable({ providedIn: 'root' })data = inject(Data)@Service()Root by default, and inject() only.TrapIf A injects B and B injects A, Angular can't create either one and throws an error.
providers: [CartStore]Its children share it.TipprovidedIn: 'root' is tree-shakable. A class in a providers array always ships in the bundle.
{ path: 'user/:id', component: User }Put the ** wildcard last.provideRouter(routes) NgModule apps use RouterModule.forRoot() .<router-outlet />routerLink="/about" :idroute.snapshot.paramMap.get('id') Or subscribe to paramMap.snapshot.queryParamMap.get('q') It holds options, like a filter.canActivate: [authGuard]canActivate, canActivateChild , canDeactivate and canMatch. Each returns a boolean or a UrlTree.resolve: { item: itemResolver }TrapNavigation waits for every resolver. Keep resolvers for small data the page can't render without.
loadComponent: () => import('./admin') loadChildren: () => import('./shop.routes') Both need a default export, or a .then() that picks the export.@defer (on viewport) { }@placeholder { }TrapDeferred components must be standalone and unused elsewhere in the file, or the build can't split them.
[(ngModel)]="name" Short for [ngModel] plus (ngModelChange).fb.group({ name: [''] })[formGroup]="form" @angular/forms/signals . Stable since 22.FormGroup from the field list.Validators.required Validators.minLength(3) null when valid, or an errors object.provideHttpClient() It replaces HttpClientModule .http.get<User[]>(url) pipe(map(r => r.data))TrapNothing is sent until something subscribes. Each subscription sends its own request.
retry(3)catchError(handle) Retry only idempotent requests, which are safe to repeat.{ provide: ErrorHandler, useClass: Log }finalize(() => loading.set(false)) withInterceptors([auth]) req.clone({ setHeaders })Requests are immutable, so change a copy.TrapOne shared boolean breaks when requests overlap. Keep a counter, often in an interceptor.
new Subject<void>()A late subscriber gets only new values.new BehaviorSubject(0) A new subscriber gets the latest value at once.new ReplaySubject(2) Value b arrives while a's request still runs. switchMap cancels a, mergeMap runs both, concatMap queues b, and exhaustMap drops b.
switchMap(q => search(q))concatMap(x => save(x))exhaustMap(c => login(c))mergeMap(id => load(id), 3)TrapDon't use switchMap for writes. Cancelling a request doesn't undo it on the server.
debounceTime(300) distinctUntilChanged() forkJoin({ users, stats })One failure fails the whole result.switchMap(u => profile(u.id))@if (user$ | async; as user) { }data = toSignal(data$)takeUntilDestroyed() It replaces takeUntil(destroy$) .TrapTwo | async on the same user$ subscribe twice, so the request runs twice. Name it once with as.
count = signal(0)count.update(n => n + 1)computed(() => count() * 2)effect(() => log(count()))user = { ...user, name }A parent passes a new objectcount.set(2)A signal read in its template changesuser.name = 'Al'A parent changes the input in placeTipOnPush is the default since Angular 22. Eager is the new name for Default.
markForCheck(). The default since 21.cdr.detectChanges() It checks its children too.cdr.markForCheck() It marks the path up to the root.TrapIn a zoneless app, zone.run() schedules no check. Update a signal or call markForCheck() instead.
track item.idThe old *ngFor used trackBy.computed or a pure pipe.cdk-virtual-scroll-viewportng new my-appng serveng g c user-cardng g s datang buildTipAOT ships no compiler, catches binding errors in the build and blocks template injection.
ng generate environmentsIt sets up fileReplacements .@angular/build:application createBuilder(fn) Rule that changes a virtual file Tree.TestBed.createComponent(Card) fixture.detectChanges() componentRef.setInput('x', 1)ng e2eIt offers Cypress, Playwright or WebdriverIO. Protractor is deprecated.{ provide: Logger, useValue: spy }provideHttpClientTesting() expectOne(url).flush(data) HttpClient, then check the request expectOne returns.ng add @angular/ssrIt replaced Angular Universal in 17.provideClientHydration() afterNextRender(fn) Trapwindow, document and localStorage don't exist on the server. Guard any code that uses them.
<p i18n>Hello</p>ng build --localizecreateCustomElement(Popup, { injector })[innerHTML]="html" Angular sanitizes it first.bypassSecurityTrustHtml(html) Never pass user input.TrapWriting to Element skips the sanitizer. Bind in the template instead.
httpOnly cookie. Any script can read localStorage.HttpClient copies the XSRF-TOKEN cookie into a header.TrapGuards only shape the UI. The server must check the token and the role on every request.
Nothing matches. Try a shorter word, or clear the search.
With Pro, you can:
Already have Pro? Sign in