Blog>
Snippets

Upgrading Existing AngularJS Components to Angular Elements

Explain the procedure for upgrading legacy AngularJS components into Angular Elements using ngUpgrade for seamless integration in modern applications.
import { Directive, ElementRef, Injector, Input, OnDestroy, OnInit } from '@angular/core';
import { UpgradeComponent } from '@angular/upgrade/static';

@Directive({
    selector: 'my-angularjs-component'
})
class MyAngularJsComponentWrapper extends UpgradeComponent implements OnInit, OnDestroy {

    @Input() someInput: string;

    constructor(elementRef: ElementRef, injector: Injector) {
        // This sets up the AngularJS component to be used in Angular
        super('myAngularJsComponent', elementRef, injector);
    }

    // Initialize the upgraded component
    ngOnInit() {
        super.ngOnInit();
    }

    // Cleanup when the Angular component is destroyed
    ngOnDestroy() {
        super.ngOnDestroy();
    }
}
This is a directive that wraps the AngularJS component enabling it to be used as an Angular component. The component is upgraded using the `UpgradeComponent` class from `@angular/upgrade/static` module. The `ngOnInit` and `ngOnDestroy` lifecycle hooks are used to initialize and clean up the component respectively.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { UpgradeModule } from '@angular/upgrade/static';

@NgModule({
    imports: [
        BrowserModule,
        UpgradeModule
    ],
    declarations: [
        MyAngularJsComponentWrapper
    ],
    entryComponents: [
        MyAngularJsComponentWrapper
    ]
})
export class MyAngularModule {
    constructor(private upgrade: UpgradeModule) {}

    ngDoBootstrap() {
        this.upgrade.bootstrap(document.body, ['myAngularJsApp'], { strictDi: true });
    }
}
This Angular module imports `UpgradeModule` from `@angular/upgrade/static`. It declares the wrapper component, and the `ngDoBootstrap` method manually boots the application, integrating the AngularJS components with the Angular application.