如何在模板中使用相同的代码而不重复

时间:2018-12-13 13:34:33

标签: twitter-bootstrap typescript angular2-template code-duplication

Angular2组件。我想在单击按钮后以模态显示相同的代码。 单击按钮后如何在模式中使用相同的HTML代码。没有重复。

html code.
...
...
...
    <div class="modal fade" id="a" tabindex="-1" role="modal" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg" role="">
    <div class="modal-content">
      <div class="modal-header">
      </div>
      <div class="modal-body">
same code here from above
...
...
...

2 个答案:

答案 0 :(得分:0)

说您有两个组成部分:  -ChildComponent  -ParentComponent

@Component({
  selector: 'child-selector',
  template: `...`,
})
export class ChildComponent {

}

然后父母

@Component({
  selector: 'parent-selector',
  template: `
    <child-selector>
    </child-selector>
  `,
})
export class ParentComponent {
  public images: Images[] = [ ... ];

  }
}

您可以查看此链接以获取详细说明:https://itnext.io/angular-patterns-2-how-to-write-seriously-reusable-components-96be16568abc

答案 1 :(得分:0)

更新为角度5并使用ngTemplateOutletContext

    <template [ngTemplateOutlet]="templateRef">
    <div class="modal fade" id="a" tabindex="-1" role="modal" 
   aria-labelledby="exampleModalLabel" aria-hidden="true">
     <div class="modal-dialog modal-lg" role="">
         <div class="modal-content">
   <div class="modal-header">
   </div>
   <div class="modal-body">
   </template>

u可以像下面一样重复上面的代码

      <template  #templateRef></template>

引用链接 How to repeat a piece of HTML multiple times without ngFor and without another @Component