函数内的Angular 2按钮小部件所有页面加载变量都是未定义的

时间:2016-12-30 05:45:31

标签: angular angular2-directives angular2-components

我为button元素创建了一个常用的小部件。

小工具 - TS:

-[UIWindow endDisablingInterfaceAutorotationAnimated:] called on <UIRemoteKeyboardWindow: 0x1024c9c00; frame = (0 0; 375 667); opaque = NO; autoresize = W+H; layer = <UIWindowLayer: 0x17022e4c0>> without matching -beginDisablingInterfaceAutorotation. Ignoring.

Widget - html:

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>

TS:

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

点击按钮后,我收到控制台消息:

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

如果我错过了为什么我没有将页面加载变量导入按钮回调函数的原因。

提前致谢。

2 个答案:

答案 0 :(得分: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);
  }

}

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

答案 1 :(得分:0)

您正在使用常规功能作为回调。 在AppButtonComponent中调用this时,AppComponent引用您的函数对象,而不是 clickEvent=()=>{ this.userString = JSON.stringify(this.user); console.info('obj = '+ this.userString); }

发送一个箭头函数,它取决于定义它的对象的范围而不是它被调用的位置。

{{1}}