【问题标题】:How can I use same code in template without duplicate如何在模板中使用相同的代码而不重复
【发布时间】:2019-05-14 17:48:26
【问题描述】:

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
...
...
...

【问题讨论】:

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


    【解决方案1】:

    假设您有两个组件: - 子组件 - 父组件

    @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

    【讨论】:

      【解决方案2】:

      更新到 angular 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>
      

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

            <template  #templateRef></template>
      

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

      【讨论】:

        猜你喜欢
        • 2017-08-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-23
        • 1970-01-01
        • 1970-01-01
        • 2016-10-07
        • 2023-03-07
        相关资源
        最近更新 更多