【发布时间】:2018-01-16 22:30:54
【问题描述】:
我想从组件中初始化并添加 onClick 方法,我该怎么做? 我只想拥有 一个 html 文件。 这是一个基本示例 - 我有一个带有这个 html 代码的寺庙文件-
<h1>h1</h1>
<h2>h2</h2>
我想继承这个组件并在h1上添加OnClick方法。
提前致谢。
【问题讨论】:
标签: html typescript angular2-template
我想从组件中初始化并添加 onClick 方法,我该怎么做? 我只想拥有 一个 html 文件。 这是一个基本示例 - 我有一个带有这个 html 代码的寺庙文件-
<h1>h1</h1>
<h2>h2</h2>
我想继承这个组件并在h1上添加OnClick方法。
提前致谢。
【问题讨论】:
标签: html typescript angular2-template
您可以只添加具有函数的组件和一个在点击时设置为 true 的变量。
<button (click)="toggleComponent()"></button>
<app-example-component *ngIf="variable">
ts:
variable = false;
toggleComponent() {
this.variable = !this.variable;
}
【讨论】:
你可以像我这样扩展组件:
Plunker 链接 https://plnkr.co/edit/azixm9?p=preview
//our root app component
import {Component, NgModule, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
@Component({
selector: 'my-app',
template: `
<div>
<h2 (click)="callMe()">Hello {{name}}</h2>
<comp-one></comp-one>
</div>
`,
})
export class App {
name:string;
constructor() {
this.name = `Angular! v${VERSION.full}`
}
public callMe(compName: any): void {
alert("App Component will handle this functionality")
}
}
@Component({
selector: 'comp-one',
template: `<h2 (click)="callMe()">Click Me</h2>`,
})
export class ComponentOne extends App {
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App, ComponentOne ],
bootstrap: [ App ]
})
export class AppModule {}
【讨论】: