티스토리 뷰

반응형

 

 

사용예시

 

<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>

 

 

두 코드는 동일한 효과를 가진다.