tap 연산자는 Observable을 디버깅 할 수 있도록 정확한 값이나, 다른 사이드 이팩트에 유용합니다.
Note: Observable의 측면에서 subscribe와는 다릅니다. 설령 subscribe하지 않은 Observable이 tap에 의해서 return되어도 , Observer에 의한 사이드 이팩트는 절대 발생하지 않습니다. tap은 단순히 존재하는 실행만 엿볼뿐, subscribe처럼 이벤트를 실행하지 않습니다.
<!-- child HTML for form --><form (ngSubmit)="onAddItem(f)" #f="ngForm"><divclass="row"><divclass="col-sm-2 form-group"><labelfor="amount">Amount</label><inputtype="number"id="amount"class="form-control"name="amount"ngModelrequiredpattern="^[1-9]+[0-9]*$"
></div></div><divclass="row"><divclass="col-xs-12"><buttonclass="btn btn-success"type="submit" [disabled]="!f.valid">Add</button><buttonclass="btn btn-danger"type="button">Delete</button><buttonclass="btn btn-primary"type="button">Clear</button></div></div></form>
-TS
// child TS
onAddItem(form: NgForm) {
const value = form.value;
const newIngredient = new Ingredient(value.amount);
this.slService.addIngredient(newIngredient);
}
NgForm을 form.value로 값에 접근할 수 있습니다.
아이템 값 불러오기 - Index이용.
1. Array에서 인덱스 값을 가져옴.
2. service를 이용하여 인덱스 값을 넘김.
3. subscribe로 child에 값을 받음.
// service.ts
startedEditng = new Subject<number>();
서비스에 subscribe할 수 있도록 Subject를 만들고, index는 number이기 때문에 제네릭 타입을 number로 지정.
-HTML
<!-- parent HTML --><ulclass="list-group"><aclass="list-group-item"style="cursor: pointer"
*ngFor="let ingredient of ingredients; let i = index"
(click)="onEditItem(i)"
>
{{ ingredient.name }} ({{ ingredient.amount }})
</a></ul>
물론 속성 값으로 [formControlName]="'username'" 를 사용해도 됩니다. string을 전달해야 하기 떄문에 ""안에 ''를 넣어야 합니다.
브라우저로 들어가 제대로 매칭이 되었는지 확인해 봅니다.
그림과 같이 ng-untouched와 같은 클래스가 있습니다.
개발 도구를 이용하면 ng로 시작하는 클래스가 있음으로, type스크립트가 작동한다는 것을 알 수 있습니다.
Validation 추가하기 - formControl 생성시 2번째 argu.에 추가합니다.
this.signupForm = new FormGroup({ //first: default Value, second: validation'username': new FormControl(null, Validators.required),
'email': new FormControl(null, [Validators.required, Validators.email]),
'gender': new FormControl('male')
});
[]를 이용하여 복수의 validation을 추가합니다.
HTML에 안내 문 추가 하기
<span
*ngIf="!signupForm.get('username').valid && signupForm.get('username').touched"
>Please enter a valid username!</span>
signupForm 객체에 들어가 valid, touched와 같은 validation 값에 접근할 수 있습니다.
구릅핑 하기 - Form Group
ts파일에 userData로 그릅핑 하겠습니다. - nested Group
'userData': new FormGroup({
'username': new FormControl(null, Validators.required),
'email': new FormControl(null, [Validators.required, Validators.email])
}),
this.signupForm = new FormGroup({
'userData': new FormGroup({
'username': new FormControl(null, Validators.required),
'email': new FormControl(null, [Validators.required, Validators.email])
}),
'gender': new FormControl('male'),
'hobbies': new FormArray([])
});
hobbies라는 FormArray를 빈 상태로 추가합니다. - 취미가 없는 사람이 있을 수 있기 때문입니다.
<divformArrayName="hobbies"><h4>Youre Hobbies</h4><buttonclass="btn btn-default"type="button"
(click)="onAddHobby()">Add Hobby</button><divclass="form-group"
*ngFor="let hobbyContrl of signupForm.get('hobbies').controls; let i = index"><inputtype="text"class="form-control" [formControlName]="i"></div></div>
HTML에 formArrayName으로 바인딩 합니다.
onAddHobby라는 매쏘드로 사용자에게 반응합니다.
몇개의 취미가 있을지 모르기 때문에 ngFor을 이용하여 FormArray에 값을 추가합니다.
클릭 이벤트 function을 상징하는 ()와 속성 바인딩 []두개가 동시에 쓰인것이 보이죠?
<inputtype='text'placeholder= "Enter stock symbol" [value]="lastStockSymbol" (input) = "lasStockSymbol=$event.target.value"><br>The value of lastStockSymbol is {{lastStockSymbol}}
service를 이용하여 DOM을 update함으로써, 2-way-binding을 구현할 수 있습니다.
#foo 로컬 레퍼런스
1. regist - input input태그를 이용하여 Angular에게 알리기를 실행해 봅니다..
ViewChild는 로컬 레퍼런스와 element를 TypeScript 코드로 변경 하기에 유용하기 때문입니다.
Form State
form태그 안쪽에 있는 input에 다음과 같은 directive를 사용할 수 있습니다.
또한 required, eail과 같은 vaild설정을 할 수 있습니다.
local reference 사용하기.
<inputtype="email"id="email"class="form-control"ngModelrequiredemail
#email="ngModel"><spanclass="help-block" *ngIf="!email.vaild && email.touched">Please enter for vaild</span>
email input태그를 선택 후 아무것도 입력하지 않고 벗어나면, please enter for vaild라는 문구가 나오게 됩니다.
#email="ngModel" 을 사용함으로써 local reference로 HTML에서 email을 사용할 수 있습니다.
<selectid="secret"class="form-control"
[ngModel]="defaultQuestion"name="secret"><optionvalue="pet">Your first Pet?</option><optionvalue="teacher">Your first teacher?</option></select>