2017-03-31 113 views
1

我有一個使用ngIf語句使用另一個組件的組件。我想只在ngIf的計算結果爲真時加載第二個組件。有沒有辦法在角度2飛鏢中加載一個組件?

編輯:發現一篇文章,幾乎可以做我需要的東西: 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; 
    } 
} 
+0

所以你真的想偷懶負載的組件而不是指令。你想要一個指令來觸發延遲加載。 –

+0

正確,一個組件。犯了一個錯誤,會編輯它 – Jonathan

回答

0

只是讓它工作。使用DynamicComponent作爲rkj答案的示例。

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

'DynamicComponent'位於何處?我無法找到並導入它。 – HoBi

+1

@HoBi,它是Angular 4中的SlowComponentLoader和Angular 2/3中的DynamicComponentLoader。 – Jonathan

2

我不認爲你可以直接做到這一點。你可以做的是使用Angular2_components的DynamicComponent,並在延遲加載之後傳遞該類型。