Angular调用函数

时间:2017-10-03 05:55:04

标签: angular

在我的角度项目中,我有以下内容:

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);
   };

}

我知道如何将数据传递给另一个指令。我想知道是否有办法直接从“main.html”或“main.ts”调用函数,如下所示:

<my_project [my_function]></my_project>

非常感谢任何帮助。

谢谢!

2 个答案:

答案 0 :(得分:1)

试试这样:

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

创建调用函数的指令

<强> 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 { }

答案 1 :(得分:0)

多次意味着究竟是什么。 1)来自同一组件的多种方式, 2)在路线负载上你需要打电话。 3)来自您想要互动的不同组件。

每种情况都有选项请具体。