我爲按鈕元素創建了一個常用的小部件。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