2016-04-03 50 views
0

我有一個指令和一個頁面(我的實際代碼的簡化版本)。當通過事件調用myMethod時,我需要myPages isTrue方法成爲true,但我不確定如何從指令訪問頁面的變量。我怎樣才能做到這一點? PS。我正在使用一個基於Angular2的框架,稱爲Ionic2。從自定義指令訪問頁面的變量

@Directive({ 
    selector: '[mySelector]' 
}) 

export class myDirective { 

    constructor() { 
    } 

    myMethod() { 
     //Make myPage's isTrue equal to true; 

    } 

} 


@Page({ 
    templateUrl: 'build/pages/myPage/myPage.html', 
    directives: [myDirective] 
}) 
export class myPage{ 

    isTrue= false; 

    constructor() {} 
} 
+1

會更好,如果可以說和顯示,1.如何使用指令在myPage? 2.你的.html如何? – micronyks

+1

閱讀[教程](https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#child-to- parent) –

回答

0

你可以在你的指令中使用自定義事件與@Output裝飾:

@Directive({ 
    selector: '[mySelector]' 
}) 
export class myDirective { 
    @Output() 
    customEvent:EventEmitter<boolean> = new EventEmitter(); 

    myMethod() { 
    this.customEvent.emit(true); 
    } 

    // Just a way to call the myMethod method 
    ngAfterViewInit() { 
    setTimeout(() => { 
     this.myMethod(); 
    }, 1000); 
    } 
} 

在組件,事件可以抓住這個方式來更新isTrue屬性:

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div mySelector (customEvent)="updateIsTrue($event)"></div> 
    <div>isTrue = {{isTrue}}</div> 
    `, 
    directives: [ myDirective ] 
}) 
export class AppComponent { 
    isTrue= false; 

    updateIsTrue() { 
    this.isTrue = true; 
    } 
} 

將此plunkr作爲示例:https://plnkr.co/edit/yuFTwMqYVNJ2awcK02gf?p=preview

另一種選擇是將組件注入指令。爲此,您需要利用forwardRef功能,因爲類吊裝不支持:

@Directive({ 
    selector: '[mySelector]' 
}) 
export class myDirective { 
    constructor(@Inject(forwardRef(() => AppComponent)) private host: AppComponent) { 

    } 

    myMethod() { 
    this.host.isTrue = true; 
    } 

    ngAfterViewInit() { 
    setTimeout(() => { 
     this.myMethod(); 
    }, 1000); 
    } 
} 

看到這個plunkr:https://plnkr.co/edit/jOlEWZzilTId3gruhu9B?p=preview