有没有办法在角2镖中延迟加载一个组件?

时间:2017-03-31 19:15:52

标签: dart lazy-loading angular2-dart

我有一个使用另一个带有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;
  }
}

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

让它成功。使用DynamicComponent作为rkj answer的示例。

// 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){}
}