Angular Standalone Component

Nahit Ferhat Ektaş
3 min readSep 26, 2023

--

Angular Standalone Component

Angular 14 ile birlikte gelen Standalone component’lar Angular kullanan veya Angular öğrenmek isteyip, sonrasında fazlaca karışık geldiğini düşünerek farklı teknolojilere yönelen geliştiriciler için oldukça radikal bir değişim oldu.

Standalone component öncesinde, oluşturduğumuz component, directive veya pipe’ larımızı kullanacağımız module’e declare etmemiz gerekiyordu. Bunun dışında aynı component, directive veya pipe’ ı birden fazla module de kullanmak istiyorsak, bu noktada işler biraz daha karışıyordu. Bunun nedeni Angular yalnızca component’imizi bir module’ e declare etmemize izin veriyor. Eğer birden fazla yerde kullanılacaksa, component’in declare edildiği module’ün diğer module’e import edilmesi gerekiyor. Bu ve buna benzer belli kurallar uygulama büyüdükçe yönetimini de biraz daha zorlaştırıyor. Bunun yanı sıra Angular öğrenme sürecini zorlaştırıyordu, bu da geliştiricileri Angular dışında alternatif framework’lere yönlendiriyordu. Standalone component’lar ile artık module den bağımsız component’lar oluşturabiliyoruz.

Component’lerimiz standalone yapmak için tek yapmamız gereken standalone:true değerini yapmaktır.

@Component({
selector: 'app-product',
standalone: true, // Standalone component
imports: [CommonModule],
templateUrl: './product.component.html',
styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {

constructor() { }

ngOnInit(): void {
}

}

Eğer component daha öncesinde bir module’ declare edilmiş ise, ilgili module’den de silinmesi gerekir. Aksi durumda hata verir.

Standalone module declaration hatası

Angular Cli ile oluşturmak için için ise,

ng generate component “componentName” — standalone kullanılabilir.

Standalone component’lerimize başka bir standalone component dahil etmek için, ilgili component’e import etmemiz yeterli olacaktır. Aşağıdaki örnekte olduğu gibi, Product component’imizi Product2 Component’ine dahil ettik.

import { Component, OnInit } from '@angular/core';
import { ProductComponent } from '../product/product.component';

@Component({
selector: 'app-product2',
standalone: true,
templateUrl: './product2.component.html',
styleUrls: ['./product2.component.css'],
imports: [ProductComponent],
})
export class Product2Component implements OnInit {
constructor() {}

ngOnInit(): void {}
}

Standalone component’leri normal component’lerimiz de kullanmak için ise, standalone component’i ilgili component’in module dosyasına import etmemiz gerekiyor.

@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
AppRoutingModule,
//Standalone component'i appModule'e import etmiş olduk.
Product2Component
],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}

Module’ ler üzerinden gerçekleşen lazy loading işlemlerini standalone component’lar ile de kolaylıkla gerçekleştirebiliriz.

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [
//module lazy loading
{
path: 'product3',
loadChildren: () =>
import('./product3/product3.module').then((m) => m.Product3Module),
},
//standalone component lazy loading
{
path: 'product',
loadComponent: () =>
import('./product/product.component').then((m) => m.ProductComponent),
},
];

@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}

Angular da CLI ile bir module oluşturduğumuzda otomatik olarak import edilen ve içerisinde *ngIf, *ngFor, formatDate vb. directive ve pipe’lerin yer aldığı common module, standalone component’ler de ihtiyaca göre hangi pipe veya directive’yi kullanacaksak ona göre import işlemi gerçekleştirebiliriz. Örneğin component’imiz de yalnızca *ngIf directive ihtiyacımız var, bunun için common module ile tüm directive ve pipe’ları import etmek yerine yalnızca *ngIf directive’yi import edebiliriz.

import { NgIf } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { ProductComponent } from '../product/product.component';

@Component({
selector: 'app-product2',
standalone: true,
template: `<div *ngIf="isActive">Angular Standalone Component</div>`,
imports: [ProductComponent, NgIf],
})
export class Product2Component implements OnInit {
isActive: boolean = true;
constructor() {}

ngOnInit(): void {}
}

Angular uygulamamızı CLI ile oluşturduğumuzda, uygulamamız ilk yüklemesini app.module.ts dosyasını kullanarak çalışacak şekilde konfigüre edilir. Yani app component’imiz standalone değildir ve app.module dosyasına declare edilmelidir. App component’imizi standalone yapmak için, uygulamanın ilk yüklendiği main.ts dosyasını açıyoruz.

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.error(err));

Yukarıda da görüldüğü gibi uygulama ilk olarak AppModule ile yükleniyor.

import { enableProdMode } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { ProductComponent } from './app/product/product.component';
import { environment } from './environments/environment';

if (environment.production) {
enableProdMode();
}

// platformBrowserDynamic().bootstrapModule(AppModule)
// .catch(err => console.error(err));

// Standalone Component ile uygulamanın yüklenmesi
bootstrapApplication(ProductComponent);

Main.ts dosyamıza uygulamamızın artık bir module ile başlatılmayacağını, onun yerine standalone component ile başlatılacağını söylemiş olduk.

--

--