【问题标题】:is there a way lazy load a component in angular 2 dart?有没有办法在 angular 2 dart 中延迟加载组件?
【发布时间】:2017-08-26 03:57:00
【问题描述】:

我有一个组件使用另一个带有 ngIf 语句的组件。一旦 ngIf 评估为 true,我只想加载第二个组件。

编辑:发现一篇几乎可以满足我需要的文章: https://medium.com/@matanlurey/lazy-loading-with-angular-dart-14f58004f988。但是,在加载库之后,它会获取组件的整个视图。就我而言,我需要将其插入到父组件的 html 中的特定位置。

类似:

import '../other/edit_component.dart' deferred as otherEdit;

@Component(
    selector: 'edit-component',
    template: '<other-component *ngIf="canOther"></other-component>
    <button type="button" (click)="go()"></button>',
    directives: const [
      otherEdit.OtherComponent
    ]
)
class EditComponent {
  @Input()
  bool canOther = false;

  go() {
    otherEdit.loadLibrary();
    canOther = true;
  }
}

【问题讨论】:

  • 所以你实际上想要延迟加载组件而不是指令。你想要一个指令来触发延迟加载。
  • 正确,一个组件。搞错了,要修改一下

标签: dart lazy-loading angular2-dart


【解决方案1】:

刚刚成功。以 rkj 答案中的 DynamicComponent 为例。

// the lib that has the component to be loaded
import 'package:somecomponent.dart' deferred as mycomponent;

class mainComponent {
  // <div #holder></div> element that we will append the component
  @ViewChild('holder', read: ViewContainerRef)
  ViewContainerRef holder;

  // this will load the component dynamically
  final DynamicComponentLoader _componentLoader;

  load() {
    // clear the html
    holder.clear();

    // load the component dynamically
    ComponentRef componentRef = await _componentLoader
      .loadNextToLocation(componentType, holder);

    // set some attributes like you would with [attributes]="somevar"
    componentRef.instance
      ..attribute = somevar;
  }

  mainComponent(this. _componentLoader){}
}

【讨论】:

  • DynamicComponent 在哪里?我找不到并导入它。
  • @HoBi,它是 Angular 4 中的 SlowComponentLoader 和 Angular 2/3 中的 DynamicComponentLoader。
【解决方案2】:

我不认为你可以直接做到这一点。您可以做的是使用 Angular2_components 中的 DynamicComponent 并在延迟加载后传递类型。

【讨论】:

    猜你喜欢
    • 2012-12-30
    • 2018-06-15
    • 1970-01-01
    • 2018-11-11
    • 2022-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-20
    相关资源
    最近更新 更多