【问题标题】:Angular 2 click event doesn't workAngular 2点击事件不起作用
【发布时间】:2017-08-14 14:36:58
【问题描述】:

我有一个 web 项目,使用 angular 2 我的不同页面使用点击事件没有任何问题,但是创建了新页面然后点击事件在新页面中出现错误。

此错误

TypeError: self.parentView.parentView.context.changedItem 不是 功能 在 View_SiteConfig3.handleEvent_0 (/AppModule/SiteConfig/component.ngfactory.js:137) 在 View_SiteConfig3.eval (core.umd.js:12399) 在 HTMLTextAreaElement.eval (platform-b​​rowser.umd.js:3223) 在 ZoneDelegate.invokeTask (zone.js:265) 在 Object.onInvokeTask (core.umd.js:3971) 在 ZoneDelegate.invokeTask (zone.js:264) 在 Zone.runTask (zone.js:154) 在 HTMLTextAreaElement.ZoneTask.invoke (zone.js:335)

site-config.html

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

site-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) {
    }
}

编辑:这个方法解决了问题;

我的项目成功了。问题是 ts 文件未编译然后给出“不是 一个函数”错误

【问题讨论】:

  • 你能发布 changedItem 方法吗?
  • 只有 changedItem 方法不起作用,我上面的所有代码都没有 app.ts 文件

标签: javascript angular


【解决方案1】:

可能是您未提供的一段代码导致的错误。

我复制了你的代码:

观点:

<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

你能提供更多代码吗?

【讨论】:

  • 我的项目成功了。问题是 ts 文件未编译,然后给出“不是函数”错误。感谢您的帮助
【解决方案2】:

试试这个:

site-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>

site-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) {
    }
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-04
  • 1970-01-01
  • 2016-08-29
  • 2016-05-13
相关资源
最近更新 更多