2017-03-22 144 views
0

我有一個web項目和使用角2我用不同的頁面使用單擊事件沒有任何問題,但創建新頁面然後單擊事件在新頁面中出現錯誤。Angular 2單擊事件不起作用

此錯誤

TypeError: self.parentView.parentView.context.changedItem is not a function at View_SiteConfig3.handleEvent_0 (/AppModule/SiteConfig/component.ngfactory.js:137) at View_SiteConfig3.eval (core.umd.js:12399) at HTMLTextAreaElement.eval (platform-browser.umd.js:3223) at ZoneDelegate.invokeTask (zone.js:265) at Object.onInvokeTask (core.umd.js:3971) at ZoneDelegate.invokeTask (zone.js:264) at Zone.runTask (zone.js:154) at HTMLTextAreaElement.ZoneTask.invoke (zone.js:335)

站點config.html

<div *ngFor="let item of items1; let i = index;" class="col-sm-4"> 
    <button (click)="changedItem(item)">Test</button> 
</div> 

站點config.ts

import { Component, OnInit } from '@angular/core' 
import { Http } from '@angular/http' 

@Component({ 
    selector: 'site-config', 
    moduleId: module.id, 
    templateUrl: '/site-config.html' 
}) 
export class SiteConfig implements OnInit { 

    items1: number[] = [1,2,3] 

    ngOnInit(): void { 
    } 

    public changedItem(item) { 
     //My Codes This Here 
    } 

    constructor(private http: Http) { 
    } 
} 

編輯:解決了這個方法的問題;

My project worked. Problem is ts file not compiled then give a "is not a function" error

+0

你能否發佈changedItem方法? –

+0

唯一changedItem方法不起作用,我的所有代碼上面沒有app.ts文件 –

回答

2

也許是從一塊的錯誤您沒有提供的代碼。

我複製你的代碼:

的觀點:

<pre *ngIf="current">{{current}}</pre> 
<div *ngFor="let item of items1; let i = index;" class="col-sm-4"> 
    <button (click)="changedItem(item)">Test</button> 
</div> 

類內容:

items1: number[] = [1,2,3] 
    current: number; 
    ngOnInit() { 
    } 

    public changedItem(item) { 
     this.current = item; 
    } 

    constructor() { 
    } 

這裏有一個工作Plunkr:https://plnkr.co/edit/ZGI1FNB8RWN9BnnPnKgJ?p=preview

你能否提供更多的代碼?

+0

我的項目工作。問題是ts文件未編譯,然後給出「不是函數」錯誤。感謝您的幫助 –

+1

沒問題!請將此答案標記爲「已接受」以關閉該主題。快樂的編碼! –

0

試試這個:

站點config.html

<div *ngFor="let item of items1; let i = index;" class="col-sm-4"> 
    <button type="button" (click)="changedItem($event, item)">Test</button> <!-- add type="button" --> 
</div> 

站點config.ts

import { Component, OnInit } from '@angular/core' 
import { Http } from '@angular/http' 

@Component({ 
    selector: 'site-config', 
    moduleId: module.id, 
    templateUrl: '/site-config.html' 
}) 
export class SiteConfig implements OnInit { 

    items1: number[] = [1,2,3] 

    ngOnInit(): void { 
    } 

    public changedItem(event: any, item: number) { 
     event.preventDefault(); 
     //Your code... 
    } 

    constructor(private http: Http) { 
    } 
}