Angular에서 ngIf Else 사용
개발자로서 웹 애플리케이션을 구축할 때 페이지를 즉석에서 조정하도록 웹 앱을 설정해야 합니다. *ngIf 문이 편리해집니다. *ngIf는 페이지에 렌더링된 HTTP 요소를 조작하는 데 사용됩니다.
일부 매개변수가 배치된 후 특정 기능을 수행하도록 웹 앱에 지시하는 조건에서 작동합니다. 그리고 그러한 매개변수가 제 위치에 없으면 대신 다른 종류를 수행해야 합니다.
*ngIf만 사용하여 일부 기능을 수행합니다. 그런 다음 *ngIf를 else 문과 결합하고 가능한 것을 확인합니다. 마지막으로 *ngIf else then 조합을 사용하여 HTTP 요소를 조작합니다.
Angular에서 *ngIf를 독립 실행형 함수로 사용
따라서 여기에서는 true 또는 false 조건과 함께 *ngIf 문을 사용합니다.
app.component.html에서 모든 작업을 수행합니다.
<h1>*ngIf in Angular</h1>
<h2 *ngIf="true">
Hi, Youtube
</h2>
*ngIf 조건이 true로 설정되면 웹페이지에 Hi, Youtube가 표시됩니다. false로 변경하면 웹페이지에서 Hi, Youtube가 사라집니다.
다음과 같이 app.component.ts를 통해 함수를 전달할 수도 있습니다.
import { Component } from "@angular/core";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
title = "CodeSandbox";
displayMe=true;
}
그런 다음 *ngIf 값을 아래와 같이 displayMe로 변경합니다.
<h1>*ngIf in ANgular</h1>
<h2 *ngIf="displayMe">
Hi, Youtube
</h2>
첫 번째 예와 마찬가지로 기본 규칙은 동일하게 작동합니다.
else와 함께 *ngIf 사용
*ngIf 조건이 else 문과 결합되면 언제든지 웹페이지에 표시할 콘텐츠를 결정하는 데 도움이 됩니다.
이 방법을 사용하려면 ng-template 태그 내 Hi, Youtube에 표시하려는 다른 문을 중첩해야 합니다.
app.component.html은 다음과 같이 표시됩니다.
<h1>*ngIf in ANgular</h1>
<h2 *ngIf="displayMe else elseBlock">
Hi, Youtube
</h2>
<ng-template #elseBlock>
<h2>
Hi, Twitter
</h2>
</ng-template>
*ngIf 조건과 함께 else 문을 사용했음을 알 수 있습니다. 이를 통해 웹페이지 콘텐츠를 더 잘 제어할 수 있습니다.
따라서 app.component.ts에서 displayMe가 true 값을 가질 때 Hi, Youtube가 표시됩니다. false인 경우 Hi, Twitter가 표시됩니다.
Angular에서 else 및 then 문과 함께 *ngIf 사용
이전 예에서 else 문과 함께 작동하는 ng-template을 소개했습니다. *ngIf 및 else와 함께 사용되는 경우 then 문을 사용하면 ng-template 내의 내용을 조작할 수 있습니다.
체계적이고 잘 정리된 코드 파일을 유지하려는 코더에게 반가운 솔루션입니다.
app.component.html은 다음과 같이 구성됩니다.
<h1>*ngIf in ANgular</h1>
<h2 *ngIf="displayMe; then ifBlock else elseBlock">
Hi, Youtube
</h2>
<ng-template #ifBlock>
<h2>
Hi, Google
</h2>
</ng-template>
<ng-template #elseBlock>
<h2>
Hi, Twitter
</h2>
</ng-template>
따라서 app.component.ts에서 displayMe가 true 값이면 Hi, Google이 표시되고 false 값이면 Hi, Twitter가 표시됩니다.
Fisayo is a tech expert and enthusiast who loves to solve problems, seek new challenges and aim to spread the knowledge of what she has learned across the globe.
LinkedIn