0

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!

4
  • why dont you place your method inside ngOnInit it will fire automatically on load ? Commented Oct 3, 2017 at 5:56
  • I should have clarified that this is being called multiple times and ngOnInit only fires once initially. Since I need to call "<my_project>" multiple times, I am looking for a way to call a function. Commented Oct 3, 2017 at 6:05
  • you need to clarify when you wish this function to be called. Otherwise we have no change of helping Commented Oct 3, 2017 at 6:11
  • 1
    you can make use of setters in Input and in that setter call that function this might help you call it multiple times when you set the value Commented Oct 3, 2017 at 6:13

2 Answers 2

1

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 { }
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.