it-source

Angular에서 템플릿 HTML 블록을 재사용하는 방법은 무엇입니까?

criticalcode 2023. 5. 1. 21:29
반응형

Angular에서 템플릿 HTML 블록을 재사용하는 방법은 무엇입니까?

파일에 html 블록이 있다고 가정합니다.

<div id="text">Text</div>

아래 HTML 코드를 같은 파일에서 어떻게 재사용할 수 있습니까, 제 말은 다음과 같은 것을 의미합니다.

<re-use id="text"></re-use>

가능합니까?

당신은 같은 html 블록을 다시 사용하고 싶었던 것 같습니다.만약 내가 당신을 올바르게 이해한다면, 아래 코드가 도움이 될 것입니다.

<ng-template #MsgRef >
        {{ mycontent }}
</ng-template>

동일한 템플릿에서 위의 블록을 재사용하려면,

 <ng-template [ngTemplateOutlet]="MsgRef"></ng-template> //reuse any number of times

새 구성 요소를 만드는 것이 가장 일반적인 방법이지만, 때때로 로컬 마크업만 반복하면 됩니다.ng-template그것을 허용합니다.

흥미로운 점은 데이터 바인딩을 사용할 수 있도록 컨텍스트를 전달할 수도 있다는 것입니다.

<ng-template #tplPerson let-person>
    <span class="person-id">{{person.id}}</span>
    <span class="person-alias" *ngIf="!!person.alias">"{{person.alias}}"</span>
    <span class="person-name">{{person.name}}</span>
</ng-template>

let-person값을 지정하지 않으면 컨텍스트 변수가 정의됩니다.person값을 로 설정한 상태에서$implicit템플릿을 인스턴스화할 때:

<ng-template *ngTemplateOutlet="tplPerson; context: {$implicit: thePerson}"></ng-template>

NgTemplateOutlet 설명서에서 추가 옵션을 참조하십시오.

파티에 늦을지도 몰라요.몇 가지 답이 있지만 위에 설명된 답으로는 달성할 수 없었습니다. 여전히 누군가가 약간의 방향성이 필요할 수 있다고 느꼈습니다.

어떤 답변에서도 명확하게 정의되지 않은 핵심 사항.

  1. 일부 값을 바인딩하는 템플릿이 있다고 가정합니다.따라서 템플릿 바인딩이 작동하려면 컨텍스트 개체를 첨부해야 합니다.

<ng-template #invoicesTemplate let-paymentInvoices="paymentInvoices">
    ...
</ng-template>
note that let-anyVariableName for template and "paymentInvoices" is the class variable that you are passing.

사용되고 있는

<ng-template *ngTemplateOutlet="invoicesTemplate; context: {paymentInvoices : paymentInvoices} "></ng-template>

  1. 템플릿을 먼저 정의한 다음 원하는 곳에서 사용해야 합니다.함수 선언을 생각해 보세요.하지만 함수를 호출하지 않는 한 아무 영향도 없습니다.

템플릿의 전체 코드 선언

<ng-template #invoicesTemplate let-paymentInvoices="paymentInvoices">
  <div class="row">
    <div class="col-sm-12">
      <div class="tags-group">
        <div class="tag" *ngFor="let invoice of paymentInvoices">
          <div class="tag-body">
            <span>{{invoice.invoiceNo }}</span>
            <span (click)="removeInvoice(invoice)"><i title="remove" >x</i></span>
          </div>
        </div>
      </div>
    </div>
  </div>
</ng-template>

전화/전화

<ng-template *ngTemplateOutlet="invoicesTemplate; context: {paymentInvoices : paymentInvoices} "></ng-template>

원하는 횟수만큼 사용할 수 있습니다.

각도를 사용하여 사용자 지정 html 태그를 생성한 후 모듈에서 해당 사용자 지정 태그를 사용할 구성 요소를 가져올 수 있습니다.그러면 HTML 페이지에서 동일한 태그를 사용할 수 있습니다.이해하는 데 도움이 될 수 있는 작은 예시를 만들었습니다.

https://stackblitz.com/edit/angular-stackoverflow

이 작업은 보다 표준적인 방법으로 사용자 지정 지침의 도움을 받아 수행할 수 있습니다.

directive.ts

import { Directive } from '@angular/core';
@Directive({
  selector: '[cardItem]'
})
export class CardItemDirective {}

component.ts

import { Component, ContentChild, Input, TemplateRef } from '@angular/core';
import { CardItemDirective } from './card-item.directive';
import { ListItemDirective } from './list-item.directive';

@Component({
  selector: 'card-or-list-view',
  templateUrl: './card-or-list-view.component.html'
})
export class CardOrListViewComponent {

  @Input() items: any[] = [];

  @Input() mode: 'card' | 'list' = 'card';

  // Read in our structural directives as TemplateRefs
  @ContentChild(CardItemDirective, {read: TemplateRef}) cardItemTemplate;
  @ContentChild(ListItemDirective, {read: TemplateRef}) listItemTemplate;

}

component.html

<ng-container [ngSwitch]="mode">
<ng-container *ngSwitchCase="'card'">
  <ng-container *ngFor="let item of items">
    <ng-container *ngTemplateOutlet="cardItemTemplate"></ng-container>
  </ng-container>
</ng-container>
<ul *ngSwitchCase="'list'">
  <li *ngFor="let item of items">
    <ng-container *ngTemplateOutlet="listItemTemplate"></ng-container>
  </li>
</ul>
</ng-container> 

링크에서 더 자세한 정보를 찾을 수 있습니다.

언급URL : https://stackoverflow.com/questions/51086407/how-to-reuse-template-html-block-in-angular

반응형