본문 바로가기
패스트캠퍼스/수업내용정리

2019-07-03 Angular forms, template-driven forms, reactive forms

by sunnykim91 2019. 7. 3.

1. Angular forms

HTML 표준 폼을 앵귤러에서는 2가지로 나뉜다.

template-driven forms : 템플릿이 복잡해지는 단점이 존재, 간단한 form에서 유리

reactive forms : form이 여러개이다 싶으면 이 형태를 쓰는게 적절

 

Form이란?

사용자의 데이터를 입력받는 인터페이스 이다. 

굉장히 친절하게 만들어져야하고, 사용하기 쉽게끔 만들어져야한다.

 

폼 데이터가 기대한  데이터 형식에 부합하는지 아닌지 체크가 필요한데 이것을 유효성 검증(form data validation)

 

 

<form action="/signup" method="POST">  // Rest api를 사용하고 있네, path를 지정하고 있으므로
    <input type="email" name="email" placeholder="Email"
      pattern="^[0-9a-zA-Z]([-_\.]?[0-9a-zA-Z])*@[0-9a-zA-Z]([-_\.]?[0-9a-zA-Z])*\.[a-zA-Z]{2,3}$"
      required>
    <input type="password" id="password1" name="password1"
      placeholder="Password" pattern="^[a-zA-Z0-9]{4,10}$"
      required>
    <input type="password" id="password2" name="password2"
      placeholder="Confirm Password" pattern="^[a-zA-Z0-9]{4,10}$"
      required>
    <input type="submit" name="submit" value="Signup">  //반드시 타입이 submit이여야함.
</form>

 

package.json default로 만드는 CLI

npm init -y

 

package.json 파일생기면 아래처럼 수정. (기존에 nodemon이 설치되어있어야함)

"scripts": {
    "start": "nodemon server.js -w"
  },

 

express 인스톨.

node i express

 

 

2.template-driven forms

<form (ngSubmit)="ngSubmitHandler(form)" #form="ngForm">   <!-- form 요소 내부에 있는 요소는 form 컨트롤 요소라고 부름.-->
      <input type="text" name="email" placeholder="email" ngModel required
      pattern="^[0-9a-zA-Z]([-_\.]?[0-9a-zA-Z])*@[0-9a-zA-Z]([-_\.]?[0-9a-zA-Z])*\.[a-zA-Z]{2,3}$"
      #email="ngModel"> 
      <input type="password" name="password" placeholder="password" ngModel
      pattern="[a-zA-Z0-9]{4,10}" required #password="ngModel">
      <button [disabled]="form.invalid">Submit</button>
 </form>    
    
    <pre>form.value: {{form.value | json}}</pre>
    <pre>form.valid: {{form.valid}}</pre>

    <pre>email.value: {{email.value | json}}</pre>
    <pre>email.valid: {{email.valid}}</pre>

    <pre>password.value: {{password.value | json}}</pre>
    <pre>password.valid: {{password.valid}}</pre>

유효성 검증 상태 프로퍼티

errors 유효성 검증에 실패한 경우, ValidationErrors 타입의 에러 객체를 반환한다. 유효성 검증에 성공한 경우, null를 반환한다.
valid 유효성 검증에 성공한 상태이면 true
invalid 유효성 검증에 실패한 상태이면 true
pristine 값을 한번도 입력하지 않은 상태이면 true
dirty 값을 한번 이상 입력한 상태이면 true
touched focus in이 한번 이상 발생한 상태이면 true
untouched focus in이 한번도 발생하지 않은 상태이면 true

 

 

반응형