事件绑定不起作用 Angular2
Event binding not working Angular2
我希望点击的 div 内容出现在另一个 div 中(通过插值)。但是当我点击 div - 我的 "view" div 里面什么也没有出现。请看下面我的代码:
@Component({
selector: 'my-app',
template: `
<div class="wrap">
<div (click)="clicked($event)">
<h2>Hello {{name}}</h2>
</div>
<div (click)="clicked($event)">
<h2>Hello {{year}}</h2>
</div>
<div (click)="clicked($event)">
<h2>Hello {{surname}}</h2>
</div>
<div (click)="clicked($event)">
<h2>Hello {{country}}</h2>
</div>
<div (click)="clicked($event)">
<h2>Hello {{cartoon}}</h2>
</div>
</div>
<div class="view">
{{target}}
</div>
`,
})
export class App {
name:string;
year: string;
surname: string;
country: string;
cartoon: string;
clicked(event) {
var target = event.target;
}
constructor() {
this.name = 'Angular2'
this.year = '1989'
this.surname = 'Connor'
this.country = 'USA'
this.cartoon = 'Tom & Jerry'
}
}
没有按预期工作。
Here's my Plunker example
我的代码有什么问题?
使用 this
绑定到模板。您正在将事件绑定到局部变量。
所以你的 class 应该是这样的:
export class App {
name:string;
year: string;
surname: string;
country: string;
cartoon: string;
element: any;
target:any;
clicked(event) {
this.target = event.target.innerText;
}
我希望点击的 div 内容出现在另一个 div 中(通过插值)。但是当我点击 div - 我的 "view" div 里面什么也没有出现。请看下面我的代码:
@Component({
selector: 'my-app',
template: `
<div class="wrap">
<div (click)="clicked($event)">
<h2>Hello {{name}}</h2>
</div>
<div (click)="clicked($event)">
<h2>Hello {{year}}</h2>
</div>
<div (click)="clicked($event)">
<h2>Hello {{surname}}</h2>
</div>
<div (click)="clicked($event)">
<h2>Hello {{country}}</h2>
</div>
<div (click)="clicked($event)">
<h2>Hello {{cartoon}}</h2>
</div>
</div>
<div class="view">
{{target}}
</div>
`,
})
export class App {
name:string;
year: string;
surname: string;
country: string;
cartoon: string;
clicked(event) {
var target = event.target;
}
constructor() {
this.name = 'Angular2'
this.year = '1989'
this.surname = 'Connor'
this.country = 'USA'
this.cartoon = 'Tom & Jerry'
}
}
没有按预期工作。 Here's my Plunker example
我的代码有什么问题?
使用 this
绑定到模板。您正在将事件绑定到局部变量。
所以你的 class 应该是这样的:
export class App {
name:string;
year: string;
surname: string;
country: string;
cartoon: string;
element: any;
target:any;
clicked(event) {
this.target = event.target.innerText;
}