2017-01-20 153 views
1

我想單擊div內容出現在另一個div(通過插值)。但是當我點擊div時,我的「視圖」div內沒有任何內容出現。請看看我的代碼如下:事件綁定不起作用Angular2

@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

這有什麼錯我的代碼?

回答

1

綁定到模板是this。您將事件綁定到局部變量。 所以,你的類應該是這樣的:

export class App { 
    name:string; 
    year: string; 
    surname: string; 
    country: string; 
    cartoon: string; 
    element: any; 
    target:any; 

    clicked(event) { 
    this.target = event.target.innerText; 
    } 

更新plunker:https://plnkr.co/edit/cnA0nGTjdsHGqCKWTQ7c?p=preview