ng-init in Angular 15

We have mostly faced this issue while migrating from AngularJS to a higher version; since the angular higher version does not support ng-init we can use the directive to achieve that,

Init Directive(ng-init.directive.js)

We can generate a directive using the following comment ng g d [directivename], which can declare the selector name which we are going to use in the element as an attribute.

And we going set the output() emitter for the directive, which is going to init for us.

@Directive({
  selector: '[ngInit]'
})
export class NgInitDirective implements OnInit {
  @Output()
    ngInit: EventEmitter<any> = new EventEmitter();

    ngOnInit() {
        this.ngInit.emit();
    }
  }

App.Module.ts for a particular module

Register the custom pipe in the module where you want to use it. For example, open the app.module.ts file and import and add NgInitDirective to the import array:

@NgModule({
  declarations: [....,....],
  imports: [
    NgInitDirective
  ],
  providers: [ ....]

App.Component.html

  1. In your component's template, pass the desired value, which needs to be initialized as parameters to the (ngInit):

By assigning the value which needs to initialize before rendering the particular <div> or <span>.

<div (ngInit)="AlreadyShown=false">
<div *ngFor="let row of data">
 ....
....
</div>
</div>


Similar Articles