티스토리 뷰
반응형
사용예시
<p *ngIf="view">hello</p>
import { Component, OnInit, ViewChild } from '@angular/core';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
view = true;
constructor() {
}
ngOnInit() {
}
}
이 경우 view 의 값이 true 이기 때문에
hello 가 출력된다.
여기서 *를 쓰는 ngIf 가 구조 디렉티브 이기 때문이다.
구조 디렉티브란 DOM 의 구조를 변형시키는 디렉티브란 뜻이다.
즉 true 인 경우에만 <p> 엘리먼트가 생성된다.
다음과 같이 응용 할 수 있다.
import { Component, OnInit, ViewChild } from '@angular/core';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
view = true;
constructor() {
}
ngOnInit() {
}
changeView() {
this.view = !this.view;
}
}
<button (click)="changeView()">btn</button>
<p *ngIf="view">hello</p>
위와 같이 코드를 수정한후 버튼을 클릭하면 클릭에 따라 p 엘리먼트가 생기고 사라지고를 반복한다.
else condition
<button (click)="changeView()">btn</button>
<p *ngIf="view">hello</p>
<p *ngIf="!view">hi</p>
<button (click)="changeView()">btn</button>
<p *ngIf="view; else hi">hello</p>
<ng-template #hi>
<p>hi</p>
</ng-template>
두 코드는 동일한 효과를 가진다.
'Angular8' 카테고리의 다른 글
[Angular] ngClass 동적으로 class 변경하기 (0) | 2020.04.07 |
---|---|
[Angular] ngStyle 동적으로 css 변경하기 (0) | 2020.04.07 |
[Angular] 양방향 바인딩 Two-Way-DataBinding (0) | 2020.04.07 |
[Angular] Event Binding 2 (0) | 2020.04.07 |
[Angular] Event Binding 1 이벤트 바인딩 (0) | 2020.04.07 |