1)
2)
login.component.ts
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { FormControl, Validators } from '@angular/forms'; // 추가!
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
@Input() visible1! : boolean; // 받는 역할
@Output() sendMyEvent : EventEmitter<any> = new EventEmitter(); // 보내는 역할
id:any = new FormControl('');
pwd:any = new FormControl('',[Validators.required, Validators.minLength(4)]);
private message :any;
constructor() { }
ngOnInit(): void {
}
styleArray = {'wrong_id':false, 'wrong_pwd':false};
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';
this.styleArray.wrong_id = true;
this.styleArray.wrong_pwd = false;
} else if(this.pwd != '1234') {
this.setMessage = 'wrong pwd';
this.styleArray.wrong_id = false;
this.styleArray.wrong_pwd = true;
}
console.log(this.id, this.pwd, this.visible1);
}
// set과 get이라는 명령어(예약어)는 함수를 마치 속성을 다루듯이 사용할 수 있게 해주는 기능입니다.
set setMessage(arg:string) { // 대입합니다.
this.message = arg;
}
get getMessage() : string{ // 가져옵니다.
return this.message;
}
}
login.component.html
<div>Wellcome</div>
<input type="text" placeholder="id" [formControl]="id" />
<input type="text" placeholder="password" [formControl]="pwd" />
<button (click)="tryToLogin()">login</button>
<!-- <div>
<span [style.color]="'blue'" *ngIf="pwd && pwd.length < 4">비밀번호 {{pwd.value}}는 4자리 이상이어야 합니다.</span>
</div> -->
<div>
<span [style.color]="'blue'" *ngIf="pwd.hasError('minlength') || pwd.hasError('required')">비밀번호 {{pwd}}는 4자리 이상이어야 합니다.</span>
</div>
<div *ngIf="getMessage" [ngClass]="styleArray">
{{getMessage}}
</div>
<!-- 속성 -->
<input type="text" [id]="'abcd'" [value]="'1234'" [class]="'cls'"/>
login컴포넌트에 설정을 하고 난 뒤에 login컴포넌트html파일에서는 hasError라는 함수에 앵귤러에서 정의된 값을 대입하여 유효성 검사여부를 확인하게 됩니다.
여기서 Validators.required는 required값이 필요하며, Validators.minLength()는 minlength 값이 필요합니다.
* html파일에서는 대소문자 구분에 유의하여 주세요.
앵귤러에서 정의된 유효성 검사에 사용가능한 항목은 'maxlength','required', 'minlength', 'pattern' 등등 다양하게 존재합니다.
'개발이 좋아서 > Angular가 좋아서' 카테고리의 다른 글
Angular - 튜토리얼10_데이터 공유(Share, Inject) (0) | 2022.09.29 |
---|---|
Angular - 튜토리얼09_데이터 바인딩 심화(로그인) (1) | 2022.09.28 |
Angular - 튜토리얼07_디렉티브(로그인) (0) | 2022.09.28 |
Angular - 튜토리얼06_컴포넌트, 모듈(로그인) (0) | 2022.09.28 |
Angular - 튜토리얼05_컴포넌트, 모듈(로그인) (0) | 2022.09.28 |