Spread the love

In angular js we have ng-init directive to process the expression or initialize the any variable in html view but in angular 2 we do not have any option to initialize variable or expression in html template, so in this tutorial we will learn how to implement ng init like functionality in angular 2 applications.
For this implementation you should knowledge of directives in angular and input output. In this article we will create a directive for ngInit and then we can use it anywhere in our app. Let’s begin with simple steps

Step 1 : Create a new custom diretive

You can simply create a custom directive using angular cli

ng generate directive myInit

this will create two files src/app/my-init.directive.ts and src/app/my-init.directive.spec.ts. It will also import the new directive to our module app.module.ts.

You can also create the file manually and add it to the modules and add simple code

import { Directive } from '@angular/core';

  selector: '[appMyInit]'
export class MyInitDirective {

  constructor() { }


Step 2: Import the new directive to module

If you have created the file manually then its required to add it into our module

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { MyInitDirective } from './my-init.directive';

  declarations: [
  imports: [
  providers: [],
  bootstrap: [AppComponent]
export class AppModule { }

Step 3 : Add logic into MyInitDirective

import { Directive, Output, EventEmitter } from '@angular/core';
  selector: '[appMyInit]'
export class MyInitDirective {

  appMyInit: EventEmitter<any> = new EventEmitter();

  ngOnInit() {


Here, we have added @Output decorator, so when we add this directive to any element then it will call the ngOnInit and then we have emitted our appMyInit.

Step 4: Using new directive into html element

Now, we are going to use our newly created directive to any element.

<h1>Angular 2 custom ngInit directive  -ReaderStacks.com </h1>

 Original Title : {{title}}

<div (appMyInit)="title2='new custom directive'">
   Updated title in html view : {{title2}}


and component

import { Component } from '@angular/core';

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
export class AppComponent {
  title = 'rest-api';


ng init in angular 2

Leave a Reply