프론트엔드/앵귤러
앵귤러 directives - ngIf
Jin-Co
2023. 1. 24. 14:29
반응형
템플릿의 구조를 변경하는 Structural directive의 하나로 한 요소에 하나의 다른 구조 디렉티브와 사용이 불가능합니다.
사용예시
1. If
<!-- ng-if1.component.html -->
<div class="container">
<hr>
<div class="card" *ngFor="let i of users">
<h3>Name: {{i.name}}</h3>
<p>Pet Owner: {{i.petOwner}}</p>
<p *ngIf="i.petOwner">Name: {{i.petName}}</p>
<hr>
</div>
</div>
// ng-if1.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-ng-if1',
templateUrl: './ng-if1.component.html',
styleUrls: ['./ng-if1.component.css'],
})
export class NgIf1Component implements OnInit {
users: {
name: string;
petOwner: boolean;
petName?: string;
}[] = [];
constructor() {}
ngOnInit(): void {
this.users = [
{ name: 'jim', petOwner: false },
{ name: 'A', petOwner: true, petName: 'B' },
{ name: 'tom', petOwner: false },
{ name: 'what', petOwner: true, petName: 'catnip' },
{ name: 'the', petOwner: false },
];
}
}
2. If else
else는 'ng-template'이라는 요소에 템플릿 변수를 지정하고 이를 if문의 else절에 삽입하는 방식으로 구현합니다.
<!-- ng-if-else.component.html -->
<div class="container">
<hr>
<div class="card" *ngFor="let i of users">
<h3>Name: {{i.name}}</h3>
<p>Pet Owner: {{i.petOwner}}</p>
<p *ngIf="i.petOwner; else noPet">Name: {{i.petName}}</p>
<ng-template #noPet>Not a pet owner</ng-template>
<hr>
</div>
</div>
// ng-if-else.component.html
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-ng-if-else',
templateUrl: './ng-if-else.component.html',
styleUrls: ['./ng-if-else.component.css']
})
export class NgIfElseComponent implements OnInit {
users: {
name: string;
petOwner: boolean;
petName?: string;
}[] = [];
constructor() {}
ngOnInit(): void {
this.users = [
{ name: 'jim', petOwner: false },
{ name: 'A', petOwner: true, petName: 'B' },
{ name: 'tom', petOwner: false },
{ name: 'what', petOwner: true, petName: 'catnip' },
{ name: 'the', petOwner: false },
];
}
}
소스코드
https://github.com/jin-co/web-mobile/tree/master/Angular/cheat-sheet/ngIf
GitHub - jin-co/web-mobile
Contribute to jin-co/web-mobile development by creating an account on GitHub.
github.com
이상으로 구조디렉티브의 하나인 ngIf에 대해서 알아보았습니다.
728x90
반응형