Steve Kim
Steve Kim

Reputation: 5611

Angular calling a function

In my angular project, I have the following:

main.html:

   <my_project [Number]="ID"></my_project> 

my_project.ts:

export class my_project {
   @Input() Number: Array<any>; 

   ...

   my_function(id){
      console.log("ID number: " +  id);
   };

}

I know how to pass data to another directive. I was wondering if there is a way to call a function directly from "main.html" or "main.ts" like below:

<my_project [my_function]></my_project>

Any help will be much appreciated.

Thanks!

Upvotes: 0

Views: 76

Answers (2)

Chandru
Chandru

Reputation: 11192

Try like this :

<my_project [my_function]="[this, 'this.name = 1; this.sampleFun()']"></my_project>

Create directive for calling a function

Component.ts

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

@Directive({
    selector: '[my_function]',
    inputs: ['my_function']
})

export class NgInitDirective {
    my_function;

    ngOnChanges() {
        if (this.my_function) {
            let iife = function(str) { return eval(str); }.call(this.my_function[0], this.my_function[1]);
        }
    }
}

@Component({
    selector: 'app-home',
    templateUrl: './home.component.html',
    styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

    constructor() { }

    ngOnInit() { }

    sampleFun() {
        console.log('hello word');
    }
}

module.ts

import {
    AppComponent,
    NgInitDirective
} from './';

@NgModule({
    declarations: [
        AppComponent,
        NgInitDirective
    ],
    entryComponents: [
        AppComponent
    ],
    providers: [],
    schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class AppModule { }

Upvotes: 1

Sharad Pathak
Sharad Pathak

Reputation: 57

Multiple times mean what exactly. 1) from same component in multiple way, 2) On route load you need to call. 3) from Different different component you want to interact.

There is option in every case please be specific.

Upvotes: 0

Related Questions