【问题标题】:Angular 4 - how to run a directive method only after its parent has fully renderedAngular 4 - 如何仅在其父级完全渲染后运行指令方法
【发布时间】:2018-06-29 01:30:11
【问题描述】:

我使用 Angular 4。我有一个指令,它是一个按钮,插入到父模板中,如下所示:

<button (emitPdfUrl)="getInvoicePdfUrl($event);" pdfButton [pdfEl]="pdf">
    <fa name="file-pdf-o"></fa> Download PDF
</button>

当父级完全呈现时,如何从指令中运行方法getPdf()?我需要这个,因为这个函数将从她父母模板的其他部分获取 innerHtml。现在发生的是,指令的函数 (getPdf()) 获得了一半显示的模板,即。没有加载父级变量的模板,因此,innerHTML 内部没有加载数据,因此该函数采用“空”模板。感谢您的任何建议! :)

【问题讨论】:

    标签: javascript angular events parent-child


    【解决方案1】:

    父组件有责任提供能够遵循所需执行顺序的方法。

    这可以通过一对 RxJS 主题来实现:

    private componentInitSubject = new AsyncSubject().ignoreElements();
    public pdfUrlSubject = new ReplaySubject(1);
    
    constructor() {
      this.pdfUrlSubscription = this.componentInitSubject
      .concat(this.pdfUrlSubject)
      .subscribe(url => this.getInvoicePdfUrl(url));
    });
    
    ngOnAfterViewInit() {
      this.componentInitSubject.complete();
    }
    
    getInvoicePdfUrl(url) {
      // starts to receive urls only after completion of componentInitSubject
    }
    

    并且可以将值发送到主题而不是直接调用getInvoicePdfUrl

    <button (emitPdfUrl)="pdfUrlSubject.emit($event)" pdfButton [pdfEl]="pdf">
    

    pdfUrlSubscription 应该在组件销毁时取消订阅。

    【讨论】:

    • 我相信这个问题是关于指令而不是组件的。 ngAfterViewInit 是一个仅限组件的钩子。 (angular.io/guide/lifecycle-hooks)
    • @AhsanAyaz 问题是inserted into the parent's template,这意味着父级是一个组件。
    • 希望对您有所帮助。
    • 它们是 RxJS 导入。通常它就像import { ReplaySubject } from 'rxjs/ReplaySubject'。见stackoverflow.com/questions/42376972/…
    • 相应地应该是import { AsyncSubject } from 'rxjs/AsyncSubject'
    猜你喜欢
    • 2012-08-27
    • 2014-04-25
    • 2017-11-25
    • 2018-01-04
    • 1970-01-01
    • 2017-10-30
    • 2021-09-11
    • 2012-12-23
    • 1970-01-01
    相关资源
    最近更新 更多