import {Component, EventEmitter, Input, OnInit, Output, ViewChild} from '@angular/core'; import {LoanModel} from '../models/loan.model'; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms'; import {ListAllLoansComponent} from '../list-all-loans/list-all-loans.component'; @Component({ selector: 'app-loan-select', templateUrl: './loan-select.component.html', styleUrls: ['./loan-select.component.scss'], providers: [ { provide: NG_VALUE_ACCESSOR, multi: true, useExisting: LoanSelectComponent } ] }) export class LoanSelectComponent implements OnInit, ControlValueAccessor { @ViewChild('list', {static: false} ) list: ListAllLoansComponent; @Input() Max = 1; // we do not support multiple loan selection at the moment @Input() readOnly = false; @Output() valueChange: EventEmitter = new EventEmitter(); public Loan: LoanModel; // for multiple selection ,it has to be array; we don't support it now. // popup public showPopup = false; public Offset = { left: 10, top: 48 }; // formControl state private disabled = false; private touched = false; // Control Value Accessor onChange = (Loan) => {}; // empty onTouched = () => {}; constructor() { } ngOnInit(): void { console.log('init loan-select', this); } writeValue(loan: LoanModel): void { this.Loan = loan; } registerOnChange(onChange: any): void { this.onChange = onChange; } registerOnTouched(onTouched: any): void { this.onTouched = onTouched; } private markAsTouched(): void { if (!this.touched) { this.onTouched(); this.touched = true; } } onLoanSelected(loan: LoanModel): void { if (this.Loan.Id !== loan.Id){ this.valueChange.emit(loan); this.onChange(loan); this.Loan = loan; } this.Loan = loan; this.markAsTouched(); this.onTouched(); this.showPopup = false; } public onToggle(): void { this.showPopup = !this.showPopup; } }