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!
asked Oct 3, 2017 at 5:55
Steve Kim
5,66117 gold badges61 silver badges100 bronze badges
-
why dont you place your method inside ngOnInit it will fire automatically on load ?Rahul Singh– Rahul Singh2017年10月03日 05:56:59 +00:00Commented 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.Steve Kim– Steve Kim2017年10月03日 06:05:31 +00:00Commented Oct 3, 2017 at 6:05
-
you need to clarify when you wish this function to be called. Otherwise we have no change of helpingkodeaben– kodeaben2017年10月03日 06:11:10 +00:00Commented Oct 3, 2017 at 6:11
-
1you 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 valueRahul Singh– Rahul Singh2017年10月03日 06:13:02 +00:00Commented Oct 3, 2017 at 6:13
2 Answers 2
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 { }
answered Oct 3, 2017 at 6:19
Chandru
11.2k6 gold badges43 silver badges54 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
lang-js