【问题标题】:typescript in ASPNET core 2 with angular - acces html document带有角度的 ASP NET Core 2 中的打字稿 - 访问 html 文档
【发布时间】:2018-07-17 23:57:15
【问题描述】:

我已经为此搜索了一段时间,但我觉得这是基础知识之一,所以没有人再费心解释它了......

这是我的问题。

我正在用 TypeScript 编写一个组件,它是 ASPNET core 2 和 Angular 项目的一部分。

TS 文件:

import { Component } from '@angular/core';

@Component({
    selector: 'clients',
    templateUrl: './clients.component.html',
    styleUrls: ['./clients.component.css']
})

export class ClientsComponent{
    rows: Array<any>;

    constructor() {
        let btn = document.getElementById("coolbutton");
        if (btn === null) return;
        btn.addEventListener("click", (e: Event) => this.ClickMeButton());
    }

    ClickMeButton() {
        alert("toto");
    }
}

HTML 文件:

<input type="button" value="Click" id="coolbutton"/>

但是页面加载时会报错:

An unhandled exception occurred while processing the request.
NodeInvocationException: Uncaught (in promise): ReferenceError: document is 
not defined

我找不到任何关于如何在我的 TS 组件中导入文档的解释...

【问题讨论】:

  • 与其尝试在组件构造函数中访问文档,不如尝试使用AfterViewInit生命周期钩子。
  • 嗨!求帮助,我现在就去看看!

标签: asp.net-mvc angular typescript .net-core


【解决方案1】:

只需将(click) 放在元素上并调用您的函数:

import { Component } from '@angular/core';

@Component({
    selector: 'clients',
    templateUrl: './clients.component.html',
    styleUrls: ['./clients.component.css']
})

export class ClientsComponent{

    constructor() {}

    public clickMeButton(): void {
        alert("toto");
    }
}

&lt;input type="button" value="Click" (click)="clickMeButton()"/&gt;

【讨论】:

  • 更简单。 after inits 似乎真的很强大,但这正是我想要的。泰!!
  • 快速提问,唯一的修改是在 HTML 中的 click 关键字周围添加括号,以及方法上的 public 修饰符(这对我来说很好:)。我在哪里可以找到这些事件的列表?假设我想在文本输入和 keyup 事件上执行此操作。
  • 嗨,这基本上是有角度的。我建议你阅读 angular 的官方文档:angular.io。有关角度事件绑定的快速概述,请参阅这篇文章:coursetro.com/posts/code/59/Angular-4-Event-Binding
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-08
  • 1970-01-01
  • 1970-01-01
  • 2021-03-02
  • 2013-12-28
  • 2017-01-12
  • 2021-03-08
相关资源
最近更新 更多