22

I want to call a function with an argument when an element is loaded. Just like nginit in angualrjs. Can we do it in Angular 4 and above?

    <div *ngFor="let item of questionnaireList"  
       (onload)="doSomething(item.id)" >
    </div>

My Typescript function:

    doSomething(id) {
        console.log(id);
    }
Emre
  • 144
  • 2
  • 17
Raj Rana
  • 419
  • 2
  • 6
  • 18

5 Answers5

19

You need to write a directive

import {Directive, Input, Output, EventEmitter} from '@angular/core';

@Directive({
  selector: '[ngInit]'
})
export class NgInitDirective {

  @Input() isLast: boolean;

  @Output('ngInit') initEvent: EventEmitter<any> = new EventEmitter();

  ngOnInit() {
    if (this.isLast) {
      setTimeout(() => this.initEvent.emit(), 10);
    }
  }
}

Using in html

<div *ngFor="let quetionnaireData of questionnairelist ; let $last = last" [isLast]='$last'
   (ngInit)="doSomething('Hello')"></div>

Also you declare your directive in app.module

@NgModule({
  declarations: [
    ..
    NgInitDirective 
  ],
  ......
})
Dakota
  • 495
  • 2
  • 10
  • Error Can't bind to 'isLast' since it isn't a known property of 'div'. @Dakota – Raj Rana Jan 19 '18 at 07:24
  • Did you add directive into declaration in module ? – Dakota Jan 19 '18 at 07:25
  • sorry but i am noob in anguilar i am declaring the directive in the app.module.ts it is not getting – Raj Rana Jan 19 '18 at 08:19
  • because there is two directive nginit and homecomponent so it is showing Unexpected value 'HomeComponent' declared by the module 'AppModule' – Raj Rana Jan 19 '18 at 08:52
  • Can you add a piece of code on your post which related to your error ex app.module,.. – Dakota Jan 19 '18 at 09:01
  • Uncaught Error: Unexpected value 'HomeComponent' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation. – Raj Rana Jan 19 '18 at 09:04
  • better u should show code of HomComponent , Hard to give you solution if only read your errror – Dakota Jan 19 '18 at 09:10
  • i have two directives export class nginitdirective { } , export class homecomponent { } . due to which there was declaration error – Raj Rana Jan 19 '18 at 09:21
  • https://stackoverflow.com/questions/46549876/please-add-a-pipe-directive-component-annotation-error . You can check your error in this question – Dakota Jan 19 '18 at 13:07
6

Use ngOnInit() and the @Input directive. For example, in your child component:

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'my-component',
  template: `
  <h3>My id is: {{itemId}}</h3>
  `
})


export class MyComponent implements OnInit
{
  @Input() itemId: string;

  //other code emitted for clarity

  public ngOnInit(): void
  {
    // Now you can access to the itemId field e do what you need
    console.log(this.itemId);     
  }
}

In your parent component

<div *ngFor="let item of questionnairelist">
    <my-component itemId='{{item.Id}}'></my-component>
</div>
Marco Barbero
  • 1,460
  • 1
  • 12
  • 22
5

Your Function:

ExecuteMyFunction(value:any):void{
    console.log(value);
}

If you wants to pass parameter which declared in component itself and set from component then try as below:

notificationMessage:string='';
@Input() message:string;

ngAfterViewInit(){
    this.ExecuteMyFunction(this.notificationMessage);
}

If you set variable as Input parameter and set from other component then try as below: ngOnChanges will fire every time when your Input variable value is changed.

import { Component, OnChanges, Input } from '@angular/core';
ngOnChanges(changes: any) {
    if (changes.message != null && changes.message.currentValue != null) {
        this.ExecuteMyFunction(this.message);
    }        
}
0

HTML:

<ng-container *ngFor="let item of items">
   <div *ngIf="doSomething(item.id)"></div>
</ng-container>

TS:

doSomething(value){
  //logic
  return true;
}
Vaibhav
  • 9
  • 2
  • 1
    Please read [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer). While this code block may answer the OP's question, this answer would be much more useful if you explain how this code is different from the code in the question, what you've changed, why you've changed it and why that solves the problem without introducing others. - [From Review](https://stackoverflow.com/review/low-quality-posts/32238228) – Saeed Zhiany Jul 20 '22 at 05:05
  • if condition call function infinite times – 13hola Jul 19 '23 at 08:25
-2
import { Router,NavigationEnd } from '@angular/router';


constructor( private router: Router ) {
 this.router.events.subscribe((e) => {
   if (e instanceof NavigationEnd) {
       // Function you want to call here
   }
 });
}
Shagun1390
  • 35
  • 1
  • 8