1

基本上,我在组件 1 的模板中有这样的东西。

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

这在组件 2 的模板中,它是组件 1 的兄弟

<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 的信息,但无法弄清楚如何在不同的组件之间共享它。有没有办法从一个组件复制模板片段并在另一个组件中使用它?

4

1 回答 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

于 2017-06-02T11:01:08.823 回答