1

複製模板的一部分基本上,我有在部件1從一個組件到另一個組件中的角4

<div> 
    <ul> 
    <li>1</li> 
    <li>2</li> 
    <li>3</li> 
    <li>4</li> 
    </ul> 
</div> 

的模板是這樣的,這在部件2的模板,其是同級COMPONENT1的

<div class="test"> 
    <h1>component 2</h1> 
</div> 

我要的是當組件2特定變量,說,"toggled" = true,組件2的模板應該是這樣的

<div class="test"> 
    <h1>component 2</h1> 
    <ul> 
    <li>1</li> 
    <li>2</li> 
    <li>3</li> 
    <li>4</li> 
    </ul> 
</div> 

我正在使用角度版本4.0.0。我閱讀了有關templateoutlet,但無法弄清楚如何在不同的組件之間共享它。有沒有辦法從一個組件複製模板片段並將其用於另一個組件?

+0

,你還可以使用,即使發射器和切換時,你得到的,使模板所需的所有值1從服務或通過發射器 –

+0

如何引用組件2中模板1中的特定代碼片段? –

回答

0

您可以使用ng-template

Injectable() 
export class TemplatePasser{ 
    template; 

} 

與模板組件:

@Component({ 
    selector:'custom' 
    template:` 

    <ng-template #template> 
     <div class="test"> 
      <h1>component 2</h1> 
     </div> 
     </ng-template> 


` 
}) 
export class CustomComponent{ 

    constructor(private templatePasser:TemplatePasser){ 


    } 
    @ViewChild('template') templateRef:TemplateRef 
    ngAfterViewInit(){ 
     this.templatePasser.template =template; 
    } 
} 


and then the other one that is using that template : 



@Component({ 
    selector:'the-other-custom' 
    template:` 

    <div *ngIf="template" class="test" style="border:1px solid red"> 
     <div [ngTemplateOutlet]="template"></div> 
     <ul> 
     <li>1</li> 
     <li>2</li> 
     <li>3</li> 
     <li>4</li> 
     </ul> 
    </div> 


` 
}) 
export class CustomComponent{ 

    constructor(private templatePasser:TemplatePasser){} 
    template 
    ngAfterViewInit(){ 
     this.template = this.templatePasser.template; 
    } 
} 

https://plnkr.co/edit/Er9Vx4qtJwc69IAQYjgD?p=preview

+0

這兩個模板都在不同的組件 –

+0

你可以傳遞模板參考服務 – Milad

+0

隨着你的解決方案,當我登錄this.template在'其他自定義'組件,它正在打印模板的正確部分。但是,在向HTML中添加'[ngTemplateOutlet] =「template」'時,會產生錯誤「templateRef.createEmbeddedView不是函數」。任何解決方案? –

相關問題