我有一个指令和一个页面(我实际代码的简化版本)。当通过事件调用myMethod时,我需要myPages isTrue方法才能变为真,但我不确定如何从指令中访问页面的变量。我该怎么做呢?PS。我使用的是一个叫做Ionic2的基于Angular2的框架。
@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() {}
}发布于 2016-04-04 14:27:01
您可以在@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;
}
}请看下面的示例: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);
}
}请参阅此选项r:https://plnkr.co/edit/jOlEWZzilTId3gruhu9B?p=preview。
https://stackoverflow.com/questions/36388556
复制相似问题