2017-07-20 25 views
1

我已經與件廠解析器工作一段時間,而我認爲這是非常漂亮,有一件事是推動我堅果。我很想將大部分重複的代碼包裝到一個呈現組件的輔助函數中。角2件廠旋轉變壓器輔助函數

在我來說,我必須在這裏我們通過改變單服務,以觸發可見性或不呈現相當多的不同組件的儀表板組件。我想知道是否有人成功地創建了一個類助手函數,可以傳遞幾個變量來實現相同的效果,從而消除了大量的重複代碼。

下面是我在一個輔助功能,並激活它的呼叫嘗試。該組件被創建,但銷燬功能不起作用。我將它縮小到實際上並未保存到全局可訪問組件的組件引用。有沒有辦法在全局數組中存儲組件引用?如果是這樣,你將如何動態訪問它們,因爲組件被添加/銷燬?內ngOnInit

認購

// Subscribe to Create User Modal Visibility 
    this._ComponentVisibilityService.createUserVisibility$.subscribe(
     _createUserVisibility => { 

      this.renderComponent(
       this.createUserModal, 
       CreateUserComponent, 
       this.createUserModalContainer, 
       _createUserVisibility 
      ) 
     } 
    ) 

功能的儀表板組件

renderComponent(component, template, container, visibility) { 

     if (visibility) { 
      // Destroy previously built components if not already destroyed 
      if (component) component.destroy(); 
      // Generate component factory 
      const componentFactory = this._ComponentFactoryResolver.resolveComponentFactory(template); 
      // Render the component 
      component = container.createComponent(componentFactory); 

     } else { 
      // Destroy the component if visibility is false 
      if (component) component.destroy() 
     } 

    } 
+0

我想你'創建與this.createUserModal'是renderComponent具有相同的邏輯。不是嗎?如果不是,'this.createUserModal'從哪裏來? –

+0

'this.createUserModal'只是儀表板組件中的一個全局變量。傳統上,這將是你從'createComponent'存儲返回的組件的地方,然後調用'this.createUserModal.destroy()'來處理它。我看到的問題(有意義)是將'createComponent'保存到函數作用域變量中,一旦函數退出,基本上會將引用返回null。 所以我想真正的問題是在哪裏保存組件引用,以便他們可以在以後的戰略交互。 – joshrathke

+0

當我看到沒有什麼錯,如果你保存'createUserModal:ComponentRef '作爲'DashboardComponent'屬性它應該讓你以後處理它,我用了一個項目,同樣的做法。 –

回答

0

內,從而結束了做一些挖掘昨晚發現,打字稿認爲any是一個基本的(原始)類型。因此,從我所知道的情況來看,沒有任何方法或結構可用於component,除非更改爲不適合「基本」類別,否則其作爲值傳遞而不是參考。然而,就像在JavaScript中,對象不被認爲是原始類型,所以我重構組件變量定投作爲對象與屬性componentComponentRef<any>,和它的工作!

組件屬性聲明

createUserModal: { component: ComponentRef<any> } = { component: null } 

函數聲明

renderModal(component: { component: ComponentRef<any> }, template, container, visibility) { 
    // Create Component... 
} 

這種組合允許對象傳遞作爲參考,這又允許該函數來改變的DashboardComponent值財產this.createUserModal,這反過來允許所有的方法被視爲正常。