2017-11-20 3 views
0

이 코드가 있습니다각도 5 GET 클래스 컨텍스트

menu.component.ts

export class menuComponent { 
    menu: object; 
    state: boolean; 

    constructor() { 
     this.state = false; 
     this.menu = [ 
      item: { 
       action: this.action 
      } 
     ] 
    } 

    action(): void { 
     this.state = !this.state; 
    } 
} 

menu.component.html을

<ul *ngFor="let item of menu"> 
    <li> 
     <a (click)="item.action()"></a> 
    </li> 
</ul> 

내가 내부 클래스의 함수와 속성을 사용할 필요가있다 액션 재미 예 : 상태 속성입니다. 이 상태에서 함수를 왜 이해하지 않지만

+1

먼저 당신이 ** 전화 ** 기능에 필요() "'. 그럼 액션이'this'에 묶여 있는지 확인해야합니다 :'action :() => this.action()'또는'action : this.action.bind (this)'. –

+1

[콜백 내부의 올바른 \'this \ '에 액세스하는 방법] 가능한 복제본 (https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) –

+0

죄송합니다. 이미 고칠 수 있습니다. – Carlos

답변

1

, 당신은 bind 사용할 수 있습니다 item.action "`(클릭) =

this.menu = [ 
     item: { 
      action: this.action.bind(this) 
     } 
    ]