2016-12-30 64 views
0

我为按钮元素创建了一个常用的小部件。Angular 2 button widget内部函数全部页面加载变量获取undefined

窗口小部件 - TS:

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

@Component({ 
    selector: 'app-button', 
    templateUrl: './app-button.component.html', 
    styleUrls: ['./app-button.component.less'] 
}) 

export class AppButtonComponent { 
//parameter 

@Input() public callback : Function; 

} 

窗口小部件 - HTML:

<button (click)="callback()" type="button">TestButton</button> 

另一组分,其中i上述按钮组件使用:

HTML:

<app-button [callback]="clickEvent"></app-button> 

TS :

import { Component, AfterViewInit, ViewChild, ContentChild, Input } from '@angular/core'; 
@Component({ 
    moduleId:"appComponent", 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.less'] 
}) 

export class AppComponent { 
user={ 
    name:"test", 
    placeholder:"plac" 
    } 
userString=''; 
    public clickEvent(){ 
     this.userString = JSON.stringify(this.user); 
     console.info('obj = '+ this.userString); 
     } 
} 

我得到如下控制台消息点击按钮后:

obj = undefined 

如果我错过了一些东西,这就是为什么我没有得到页面加载可变进按钮回调函数。

在此先感谢。

回答

0

对于来自指令和组件发射自定义事件的建议使用EventEmitter

所以进行下列变更的检查一遍:

//控件

import { Component, Output, EventEmitter, HostListener, OnInit } from '@angular/core'; 

@Component({ 
    selector: 'app-button', 
    templateUrl: './app-button.component.html', 
    styleUrls: ['./app-button.component.less'] 
}) 

export class AppButtonComponent { 
    //parameter 

    @EventEmitter() public callback: EventEmitter<any> = new EventEmitter(); 

    public onClick(e) { 
    this.callback.emit(e); 
    } 

} 

//控件的HTML

<button (click)="onClick($event)" type="button">TestButton</button> 

//用法

<app-button (callback)="clickEvent($event)"></app-button> 

// Compoenent

export class AppComponent { 
    public userString:string = ''; 
    public user: any = { 
    name:"test", 
    placeholder:"plac" 
    }; 

    public clickEvent(){ 
    this.userString = JSON.stringify(this.user); 
    console.info('obj = '+ this.userString); 
    } 
} 
+0

谢谢Kunal。我没有在控制台中得到未定义的错误。但是这种方法在页面加载时触发。 // widget TS @Output()public callback:EventEmitter = new EventEmitter(); //组件HTML <应用程序按钮[回调] = “clickEvent()”> 如果我通过参数转换clickEvent方法 “$事件” 我得到控制台错误。 我使用错误的均衡器? –

+0

使用'EventEmitter'我们必须将事件绑定到''not'' – ranakrunal9

+0

要知道有关事件绑定的更多信息,请访问https:// angular。io/docs/ts/latest/guide/template-syntax.html#!#event-binding – ranakrunal9

0

您使用普通函数作为回调。 在AppButtonComponent中调用时,this引用您的函数对象,而不是AppComponent

改为发送一个箭头函数,它取决于它所在的对象的范围,而不是它被调用的地方。

clickEvent=()=>{ 
     this.userString = JSON.stringify(this.user); 
     console.info('obj = '+ this.userString); 
     }