Created
June 2, 2019 20:20
-
-
Save fabiobiondi/d07db91bf8ce4f9e33967f4fcc5a685c to your computer and use it in GitHub Desktop.
Angular 8: Custom Form Control (stars) with Control Value Accessor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component, OnInit } from '@angular/core'; | |
import { FormBuilder, FormGroup, Validators } from '@angular/forms'; | |
@Component({ | |
selector: 'app-demo', | |
template: ` | |
<form [formGroup]="form"> | |
<input type="text" formControlName="yourname"> | |
<app-stars formControlName="stars"></app-stars> | |
</form> | |
<pre> | |
{{form.valid}} | |
{{form.touched}} | |
{{form.get('stars').errors | json}} | |
</pre> | |
` | |
}) | |
export class DemoComponent implements OnInit { | |
form: FormGroup; | |
constructor(private fb: FormBuilder) { | |
this.form = fb.group({ | |
yourname: ['', Validators.required], | |
stars: [null, Validators.required] | |
}); | |
} | |
ngOnInit() { | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component, forwardRef, Input, OnInit } from '@angular/core'; | |
import { AbstractControl, ControlValueAccessor, NG_VALIDATORS, NG_VALUE_ACCESSOR, ValidationErrors, Validator } from '@angular/forms'; | |
@Component({ | |
selector: 'app-stars', | |
providers: [ | |
{ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => StarsComponent), multi: true }, | |
], | |
template: ` | |
<div> | |
<i | |
*ngFor="let star of [null,null,null]; let i = index" | |
style="cursor: pointer" | |
class="fa" | |
(click)="onClickStarHandler(i+1)" | |
[ngClass]="{ | |
'fa-star': i+1 <= value, | |
'fa-star-o': i+1 > value | |
}" | |
></i> | |
</div> | |
`, | |
}) | |
export class StarsComponent implements ControlValueAccessor { | |
value: number; // 1,2,3 | |
onChanged: (val) => void; | |
onTouched: () => void; | |
registerOnChange(fn: any): void { | |
this.onChanged = fn; | |
} | |
registerOnTouched(fn: any): void { | |
this.onTouched = fn; | |
} | |
writeValue(val: number): void { | |
this.value = val; | |
} | |
onClickStarHandler(value: number) { | |
this.value = value; // update UI | |
this.onChanged(value); | |
this.onTouched(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment