본문 바로가기

개발 공부/Angular

ng-template / Angular (1)

Angular ng-template

ng-template은 Angular의 HTML 템플릿 요소입니다.

일반 HTML과는 달리, 브라우저에서 기본적으로 렌더링되지 않으며 Angular가 필요할 때 동적으로 렌더링합니다.

이 점은 조건부 렌더링, 반복 렌더링, 그리고 재사용 가능한 템플릿을 정의할 때 매우 유용합니다.

 

특징:

  1. 화면에 직접 렌더링되지 않음 (비활성 상태로 존재)
  2. Angular의 디렉티브와 함께 사용하여 특정 조건에서만 렌더링 가능
  3. ng-template 내부의 HTML은 동적으로 구성 가능
<!-- ng-template을 정의 -->
<ng-template>
  <p>이 텍스트는 화면에 즉시 렌더링되지 않습니다.</p>
</ng-template>

 

위 코드는 ng-template 내부의 텍스트를 정의하지만, 브라우저 화면에는 아무것도 표시되지 않습니다.

Angular가 명시적으로 렌더링을 지시할 때만 나타나게 됩니다.

 

ng-template의 기초 활용

1. 조건부 렌더링

 

조건부 렌더링은 Angular 애플리케이션에서 자주 사용되는 패턴입니다.

ng-template과 ngIf를 조합하여 특정 조건에서만 콘텐츠를 렌더링할 수 있습니다.

<ng-container *ngIf="isVisible; else elseTemplate">
  <p>이 콘텐츠는 isVisible이 true일 때 나타납니다.</p>
</ng-container>

<ng-template #elseTemplate>
  <p>이 콘텐츠는 isVisible이 false일 때 나타납니다.</p>
</ng-template>

 

TypeScript

import { Component } from '@angular/core';

@Component({
  selector: 'app-conditional-rendering',
  templateUrl: './conditional-rendering.component.html',
})
export class ConditionalRenderingComponent {
  isVisible = true;

  toggleVisibility() {
    this.isVisible = !this.isVisible;
  }
}

 

 

  • ng-container는 HTML DOM에 추가되지 않고, Angular가 요소를 그룹화할 때 사용합니다.
  • *ngIf는 조건부 렌더링을 담당하며, 조건이 false일 때 else 키워드와 ng-template을 사용해 대체 콘텐츠를 렌더링합니다.
  • toggleVisibility() 함수는 isVisible 값을 변경하여 렌더링되는 콘텐츠를 동적으로 전환합니다.

 

2. 반복 렌더링

 

ng-template은 ngFor와 함께 사용할 때도 유용합니다.

이는 반복적으로 렌더링해야 하는 항목을 동적으로 정의하는 데 적합합니다.

<ng-template ngFor let-item [ngForOf]="items">
  <p>{{ item }}</p>
</ng-template>

 

 

TypeScript

import { Component } from '@angular/core';

@Component({
  selector: 'app-repeat-rendering',
  templateUrl: './repeat-rendering.component.html',
})
export class RepeatRenderingComponent {
  items = ['Angular', 'React', 'Vue'];
}

 

  • ng-template은 반복되는 각 항목에 대해 별도의 DOM 노드를 생성합니다.
  • 위 코드는 items 배열의 각 항목을 <p> 태그로 출력합니다.

 

3.ngSwitch와 ng-template의 연계 사용

ngSwitch는 여러 조건 중 하나에 해당하는 템플릿을 렌더링할 때 사용됩니다.

이때 각 조건의 템플릿은 ng-template을 통해 정의합니다.

<div [ngSwitch]="currentView">
  <ng-template [ngSwitchCase]="'home'">
    <p>홈 화면입니다.</p>
  </ng-template>
  <ng-template [ngSwitchCase]="'about'">
    <p>소개 화면입니다.</p>
  </ng-template>
  <ng-template [ngSwitchCase]="'contact'">
    <p>연락처 화면입니다.</p>
  </ng-template>
  <ng-template ngSwitchDefault>
    <p>기본 화면입니다.</p>
  </ng-template>
</div>

 

TypeScript

import { Component } from '@angular/core';

@Component({
  selector: 'app-switch-example',
  templateUrl: './switch-example.component.html',
})
export class SwitchExampleComponent {
  currentView = 'home';

  changeView(view: string) {
    this.currentView = view;
  }
}

 

 

  • ngSwitch 디렉티브는 currentView 값에 따라 적합한 템플릿을 렌더링합니다.
  • ngSwitchCase는 특정 조건에 맞는 템플릿을 정의합니다.
  • ngSwitchDefault는 조건이 모두 일치하지 않을 때 렌더링되는 기본 템플릿을 나타냅니다.

 

동작 화면 확인

  1. 초기 currentView 값이 'home'이므로 "홈 화면입니다."라는 텍스트가 렌더링됩니다.
  2. 버튼을 추가하여 currentView를 변경해 봅시다.
<button (click)="changeView('home')">Home</button>
<button (click)="changeView('about')">About</button>
<button (click)="changeView('contact')">Contact</button>
<div [ngSwitch]="currentView">
  <ng-template [ngSwitchCase]="'home'">
    <p>홈 화면입니다.</p>
  </ng-template>
  <ng-template [ngSwitchCase]="'about'">
    <p>소개 화면입니다.</p>
  </ng-template>
  <ng-template [ngSwitchCase]="'contact'">
    <p>연락처 화면입니다.</p>
  </ng-template>
  <ng-template ngSwitchDefault>
    <p>기본 화면입니다.</p>
  </ng-template>
</div>

 

  • 버튼을 클릭할 때마다 currentView가 변경되며, 이에 따라 적합한 템플릿이 렌더링됩니다.

'개발 공부 > Angular' 카테고리의 다른 글

ng-template / ng-container 차이  (1) 2024.12.10
ng-template / Angular (2)  (0) 2024.12.08
ng-container / Angular (2)  (0) 2024.12.02
ng-container / Angular (1)  (1) 2024.12.01
Query Parameters / Angular  (1) 2024.11.26