Skip to content

Latest commit

 

History

History
157 lines (118 loc) · 5.35 KB

06. SelectorAndDirective.md

File metadata and controls

157 lines (118 loc) · 5.35 KB

06. Selector

component에서 selector 부분을 함 봐 볼까요? app 컴포넌트 html 파일에 login 컴포넌트의 셀렉터를 html 태그처럼 붙여놨었다.

컴포넌트 ts파일에 존재하는 셀렉터 값이 다른 컴포넌트 html 파일 또는 index.html 파일에 사용된다.

컴포넌트와 컴포넌트간의 데이터 주고 받는 방법

컴포넌트간의 데이터 공유는 input 데코레이터, output 데코레이터를 활용한다.

app 컴포넌트에서 loginBool 변수가 있었다. 해당 값을 login 컴포넌트에 전달하기 위해서 login 컴포넌트의 셀렉터 태그에 아래처럼 데이터를 전달했다.

06. Directive

import { Component, Input, OnInit, Output,EventEmitter } from '@angular/core';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  @Input() visible1 : boolean = false; // 받는 역할
  @Output() sendMyEvent : EventEmitter<any> = new EventEmitter(); //보내는 역할
  id: string ='';
  pwd:string ='';
  private message :any;

  constructor() { 

  }

  ngOnInit(): void {
  }

  tryToLogin() : void{
    if(this.id == 'admin' && this.pwd == '1234'){
      alert('로그인 합니다!');
      this.visible1 = true;
      this.sendMyEvent.emit(this.visible1); // app 컴포넌트에 전달한다. 
    }else if(this.id != 'admin'){
      this.setMessage = 'wrong id';
    }
    else if(this.pwd != '1234'){
      this.setMessage = 'wrong pwd'
    }
    console.log(this.id, this.pwd);
    this.sendMyEvent.emit(this.visible1); // 보낸다! 
  }

  set setMessage(str: string){ // 대입합니다
    this.message = str;
  }
  get getMessage() :any{
    return this.message;
  }
}

set, get 함수가 보인다.

set,get 이라는 명령어(예약어)는 함수를 마치 속성 다루듯이 사용할 수 있게 해 주는 기능이다. 이러한 기능을 활용하면 함수를 변수처럼 간단하게 사용할 수 있다.

login.component.html

ngClass : CSS class 들을 추가하고 지워준다.

login.component.ts

styleArray = {'wrong_id':false, 'wrong_pwd':false};

login.component.html

<div>Wellcome</div>
<input type="text" placeholder="id" [(ngModel)]="id"/>
<input type="text" placeholder="password" [(ngModel)]="pwd"/>
<button (click)="tryToLogin()">Login</button>
<div>
    <span *ngIf="pwd && pwd.length < 4">비밀번호 {{pwd}}는 4자리 이상이어야 합니다. </span>
</div>
<div *ngIf="getMessage" [ngClass]="styleArray">
    {{getMessage}}
</div>

ngClass는 앵귤러에서 제공하는 디렉티브다. html 태그에 클래스를 동적으로 부여할 때 사용 가능하다. 단순하게 대입 연산자로도 할 수 있고 배열 형식으로도 할당 가능하다.

위의 예시는 key, value 형태의 json 형식에서의 클래스 적용 방법이다.

directive 라고 불리우는 기능은 html 과 관련된 직접적인 행동을 담당한다.

ngClass 같은 디렉티브를 속성 디렉티브라고 한다.

🎄 Attribute Directive : 속성 디렉티브

속성 디렉티브는 HTML 요소의 문양, 동작 등을 제어할 때 사용된다.

💍 Structural directive : 구조 디렉티브

조건이나 반복문처럼 사용한 HTML 태그의 구조(Control Dom)를 변경할 때 사용 한다.

ngIf 나 ngFor 같은 디렉티브는 마찬가지로 디렉티브이며 구조 디렉티브라고 한다. Structural directive

한가지 더 해 봅시다..

🧸 Attribute :

HTML 태그 자체의 속성에 대한 값을 변경할 때 사용된다.

login.component.html

<div>Wellcome</div>
<input type="text" placeholder="id" [(ngModel)]="id"/>
<input type="text" placeholder="password" [(ngModel)]="pwd"/>
<button (click)="tryToLogin()">Login</button>
<div>
    <span [style.color]="'blue'"  *ngIf="pwd && pwd.length < 4">비밀번호 {{pwd}}는 4자리 이상이어야 합니다. </span>
</div>
<div *ngIf="getMessage" [ngClass]="styleArray">
    {{getMessage}}
</div>

여기 style.color 를 추가 해 주었죠 ! 여기서 style은 디렉티브가 아닌 속성(Attribute)을 의미합니다. HTML 태그 자체의 속성에 대한 값을 변경할 때 사용됩니다

마찬가지로 대입연산자를 통해서 컴포넌트.ts 파일에 있는 값을 붙여 (바인딩) 줄 수 있다. 디렉티브와 다르므로 헷갈리면 안된다!

속성은 사실 app.component.html 에서 경험해본적 있다! 바로 [visible1] 값이다 !

<app-login  [visible1]="loginBool" (sendMyEvent)="getEventThanks($event)"></app-login>

html 파일에서 ng로 시작하면서 [] 로 감싼 형태는 대부분 디렉티브 에 해당한다.

html 에서 사용되는 value, id, class 같은 속성(Attribute)이나 위 처럼 컴포넌트에 전달하는 데이터를 사용하는 경우 대부분 속성 (Attribute) 이라고 한다.

정리 ✨

  1. Attribute directive(속성 디렉티브) : html 관련된 모양, 동작 제어 (ngClass, ngStyle 등)
  2. Structural directive(수조 디렉티브) : 구조를 변경할 때 사용된다 (ngIf, ngFor, ngSwitch 등)
  3. Attribute(속성) : HTML 속성에 값을 지정한다. (style, value, class 등)

참조

앵귤러 튜토리얼(Angular tutorial) - 11 : 디렉티브