donaricano-btn

앵귤러2  ngIf를 이용한 엘리먼트 제어


1. ngIf

- 엘리먼트를 보이거나 숨기는 역할을 한다

1) 종류

1
2
3
<div *ngIf="상태">...</div>
<div template="ngIf 상태">...</div>
<template [ngIf]="상태"><div>...</div></template>


2. ngIf 예제

1) app.component.ts

1
2
3
4
5
6
7
8
9
10
11
import { Component } from '@angular/core';
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
 
  public gender = 1;
}

2) app.component.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<select [(ngModel)]="gender">
  <option value=1>man</option>
  <option value=2>woman</option>
</select>
 
<h2 *ngIf="gender==1">choice man</h2>
<h2 *ngIf="gender==2">choice woman</h2>
 
<h3>
  <span template="ngIf gender==1">choose a man</span>
  <span template="ngIf gender==2">choose a woman</span>
</h3>
 
<h4>
  <template [ngIf]="gender==1">man</template>
  <template [ngIf]="gender==2">woman</template>
</h4>

블로그 이미지

리딩리드

,
donaricano-btn

앵귤러2  ngClass 를 이용한 class 추가 제거


1. ngClass

- class의 클래스 이름을 더하거나 해제하는 속성 지시자


2. ngClass 예제

1) app.component.ts

1
2
3
4
5
6
7
8
9
10
11
12
import { Component } from '@angular/core';
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
 
  public isActive: boolean = false;
  myclass: string="active";
}

2) app.component.html

1
2
3
4
5
6
7
8
9
<button class="button" [ngClass]="{active: isActive}"
 
(click)="isActive=!isActive;">{{isActive?'활성':'비활성'}}</button><br>
 
<button [ngClass]="myclass">버튼1</button>
<button [ngClass]="'active'">버튼2</button>
<button bind-ngClass="myclass">버튼3</button><br>
<button [attr.class]="myclass">버튼4</button>
<button [class.active]="true">버튼5</button>

- 첫번 째 버튼은 토글형식으로 변한다

- 1~3 버튼은 ngClass 속성 지시자를 사용

3) app.component.css

1
2
3
4
5
6
7
8
9
10
11
12
button{
  width:100px;
  padding:10px;
  margin-bottom: 10px;
  text-align : center;
  border : 1px dotted #666;
}
 
button.active{
  background-color:#CFD7EB;
  border: 1px solid #666;
}

블로그 이미지

리딩리드

,
donaricano-btn

앵귤러2  HelloWorld Service - 서비스 사용하기


1. 서비스의 역할

1). 애플리케이션 관심사와 개별 컴포넌트 관심사의 분리

- 모든 컴포넌트의 공통적으로 존재하는 공통 관심 기능을 서비스로 만든다.

2). 컴포넌트 중간에서 데이터 중개자의 역할

- 컴포넌트 사이의 느슨한 연결을 하면서 데이터 교환의 중개인 역할을 한다.

3). 관심사의 분리

- 데이터 서비스, 로깅 서비스, 비즈니스 로직 서비스와 같은 관심사를 각각 다르게 컴포넌트에 적용 할 수 있다.

4). 코드 재사용성 향상


2. HelloWorld 서비스

1) hello.service.ts

- $ ng g service hello

1
2
3
4
5
6
7
8
9
10
11
12
import { Injectable } from '@angular/core';
 
@Injectable()
export class HelloService {
 
  sayHello(){
    return "Hello Service";
  }
 
  constructor() { }
 
}

- @Injectable은 주입 가능하는 클래스를 의미 한다.

2) hello.component.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import { Component, OnInit } from '@angular/core';
import {HelloService} from "../hello.service";
 
@Component({
  selector: 'app-hello',
  templateUrl: './hello.component.html',
  styleUrls: ['./hello.component.css'],
  providers:[HelloService]
})
export class HelloComponent implements OnInit {
 
  welcome : string;
 
  constructor(private helloService:HelloService) {
    this.welcome = helloService.sayHello();
  }
 
  ngOnInit() {
  }
 
}

- providers라는 키워드를 이용하여 서비스를 등록해야 사용가능하다. 이후 생성자를 통한 객체의 의존주입을 한다.

- new 키워드를 이용하여 객체를 생성해도 문제없다.  그러나 추천하지 않는다.

1
2
let hello = new HelloService();
this.welcome = hello.sayHello();

블로그 이미지

리딩리드

,
donaricano-btn

앵귤러2 컴포넌트 사이 값 전달(@Input 장식자, inputs속성)


- 컴포넌트 사이(부모, 자식) 의 값을 전달하는 방법에 세가지가 있다

- @Input 장식자, inputs 속성, EventEmitter

- @Input 장식자와 inputs 속성은 부모 -> 자식으로 값을 전달

- EventEmitter 는 자식 -> 부모로 값을 전달


1. @Input장식자

- 외부에서 전달된 값을 받기 위해 사용하는 장식자

- 부모 컴포넌트에서 자식 컴포넌트로 값을 전달 한다

1) parant.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import { Component, OnInit } from '@angular/core';
 
@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
 
  constructor() {
  }
 
  ngOnInit() {
  }
   
  fruit1="apple";
   
  fruit2(){
    return "pale";
  }
   
  fruit3 = ['strawberry','grape'];
   
  static fruit5="watermelon";
   
  get fruit6(){
    return ParentComponent.fruit5;
  }
 
}

- 부모 컴포넌트에 넘겨줄 값을 선언한다.

2) parent.html

1
2
3
4
5
<div>
  parent
<app-child [name1]="fruit1" [name2]="fruit2()" [name3]="fruit3" [name4]="1+1"
 [name5]="fruit5" [name6]="fruit6"></app-child>
</div>

-  자식 컴포넌트 태그에 name 속성에 값을 전달

3) child.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { Component, OnInit, Input } from '@angular/core';
 
@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
 
  constructor() {
  }
 
  ngOnInit() {
  }
 
  @Input() name1: string;
  @Input() name2: string;
  @Input() name3: string[];
  @Input() name4: number;
  @Input() name5: string;
  @Input() name6: string;
 
}

- @Input 장식자를 이용하여 값을 받는다

4) child.html

1
2
3
4
5
6
7
8
<div>
  name1:{{name1}}<br>
  name2:{{name2}}<br>
  name3:{{name3}}<br>
  name4:{{name4}}<br>
  name5:{{name5}}<br>
  name6:{{name6}}
</div>


2. inputs 속성

- 컴포넌트 장식자 설정의 inputs 속성을 통해서도 값을 받는 것이 가능하다

- @Input  장식자와 다르게 @Component 장식자 내부에 inputs 속성을 추가한다.

1) parent.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { Component, OnInit } from '@angular/core';
 
@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
 
  ngOnInit(){
 
  }
   
  name1 = "apple";
  name2 = "banana";
 
}

2) parent.html

1
2
3
4
<div>
  parent
<app-child [name1]="name1" [name2]="name2" ></app-child>
</div>

- name 속성을 전달한다.

3) child.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { Component, OnInit, Input } from '@angular/core';
 
@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css'],
  inputs:['name1','name2']
})
export class ChildComponent implements OnInit {
 
  ngOnInit(){
 
  }
 
  name1: string;
  name2: string;
 
}

-@Component 에 inputs 속성을 추가하여 값을 받는다.


3. EventEmitter

- 자식 컴포넌트에서 부모 컴포넌트로 값을 전달 할때 사용한다.

- @Output 장식자로 선언한 변수를 EventEmitter 로 초기화한다. 이후 emit()을 사용하여 부모로 이벤트 전달한다.

1) child.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
 
@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
 
  ngOnInit(){
 
  }
   
  active = false;
  @Output() outputProperty = new EventEmitter<boolean>();
   
  updateParent(active: boolean){
    this.active = !active;
    this.outputProperty.emit(this.active);
  }
   
}

- new EventEmitter<boolean> , EventEmitter 객체의 자료형은 boolean을 선언했다.

- boolean 선언으로 emit()의 값을 넘겨줄 때 boolean 으로 넘어가며 받는 컴포넌트(부모)도 동일하게 선언해야 한다

- emit() 를 통해 부모 컴포넌트에 값 전달

- this.outputProperty.emit(this.active)

2) parent.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { Component, OnInit } from '@angular/core';
 
@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
 
  ngOnInit(){
 
  }
 
  cntClick = 0;
   
  active = false;
   
  outputEvent(active: boolean){
    this.cntClick++;
    this.active = active //자식에게 받은값
  }
 
}

3) parent.html

1
2
3
4
5
6
<div>
  parent<br>
  clickCnt : {{cntClick}}<br>
  childStatus:{{active}}
<app-child (outputProperty)="outputEvent($event)"></app-child>
</div>

- 부모 컴포넌트의 값을 자식 컴포넌트가 값을 받을 때는 @Output 장식자로 선언한 변수와 동일한 속성명으로 받는다

블로그 이미지

리딩리드

,