我为按钮元素创建了一个常用的小部件。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
如果我错过了一些东西,这就是为什么我没有得到页面加载可变进按钮回调函数。
在此先感谢。
谢谢Kunal。我没有在控制台中得到未定义的错误。但是这种方法在页面加载时触发。 // widget TS @Output()public callback:EventEmitter = new EventEmitter(); //组件HTML <应用程序按钮[回调] = “clickEvent()”> 如果我通过参数转换clickEvent方法 “$事件” 我得到控制台错误。 我使用错误的均衡器? –
使用'EventEmitter'我们必须将事件绑定到' 'not'' –
ranakrunal9
要知道有关事件绑定的更多信息,请访问https:// angular。io/docs/ts/latest/guide/template-syntax.html#!#event-binding – ranakrunal9