首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从自定义指令访问页面的变量

从自定义指令访问页面的变量
EN

Stack Overflow用户
提问于 2016-04-04 01:17:03
回答 1查看 72关注 0票数 0

我有一个指令和一个页面(我实际代码的简化版本)。当通过事件调用myMethod时,我需要myPages isTrue方法才能变为真,但我不确定如何从指令中访问页面的变量。我该怎么做呢?PS。我使用的是一个叫做Ionic2的基于Angular2的框架。

代码语言:javascript
复制
@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() {}
}
EN

回答 1

Stack Overflow用户

发布于 2016-04-04 14:27:01

您可以在@Output装饰器的指令中使用自定义事件:

代码语言:javascript
复制
@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属性:

代码语言:javascript
复制
@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函数,因为不支持类提升:

代码语言:javascript
复制
@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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36388556

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档