Custom Select Component (AngularForm)
Zur Navigation springen
Zur Suche springen
import { Component, OnInit, forwardRef, Input } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; import { VideoArchiveService } from 'src/app/shared/video-archive.service'; @Component({ selector: 'vac-actor-country-combo-box', templateUrl: './actor-country-combo-box.component.html', styleUrls: ['./actor-country-combo-box.component.css'], providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => ActorCountryComboBoxComponent), multi: true } ] }) export class ActorCountryComboBoxComponent implements OnInit, ControlValueAccessor { @Input() name: string; // tslint:disable-next-line:no-input-rename @Input('value') val: string; isDisabled: boolean; private countries: string[]; onChange: any = () => { }; onTouched: any = () => { }; constructor( private videoService: VideoArchiveService ) { } ngOnInit() { this.videoService.getActorCountries().subscribe(countries => this.countries = countries); } get value() { return this.val; } set value(val) { this.val = val; this.onChange(val); this.onTouched(); } writeValue(value: any): void { if (value) { this.val = value; } else { this.val = ''; } } registerOnChange(fn: any): void { this.onChange = fn; } registerOnTouched(fn: any): void { this.onTouched = fn; } setDisabledState(isDisabled: boolean) { this.isDisabled = isDisabled; } }
<select *ngIf=isDisabled [name]="name" [(ngModel)]="value" disabled> <option value=""></option> <option *ngFor="let country of countries" [value]="country">{{country}}</option> </select> <select *ngIf=!isDisabled [name]="name" [(ngModel)]="value"> <option value=""></option> <option *ngFor="let country of countries" [value]="country">{{country}}</option> </select>
Zurück zu Angular