Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: I want to call a function when element is loaded

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);
    }
like image 857
Raj Rana Avatar asked Jan 19 '18 07:01

Raj Rana


4 Answers

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 
  ],
  ......
})
like image 191
Dakota Avatar answered Oct 19 '22 21:10

Dakota


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>
like image 27
Marco Barbero Avatar answered Oct 19 '22 19:10

Marco Barbero


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);
    }        
}
like image 5
Sandip - Frontend Developer Avatar answered Oct 19 '22 20:10

Sandip - Frontend Developer


HTML:

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

TS:

doSomething(value){
  //logic
  return true;
}
like image 1
Vaibhav Avatar answered Oct 19 '22 19:10

Vaibhav