2017-01-20 4 views
1

클릭하면 다른 div 안에 보일 것입니다 (보간법을 통해). 그러나 div를 클릭하면 내 "view"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