import { Component , Input , OnDestroy , OnInit } from '@angular/core' ; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap' ; import { AbstractControl , FormControl , FormGroup , ValidatorFn , Validators } from '@angular/forms' ; import { RenderResult } from '../../../models/cmdb-render' ; import { checkObjectExistsValidator , ObjectService } from '../../../services/object.service' ; import { ReplaySubject } from 'rxjs' ; import { takeUntil } from 'rxjs/operators' ; @ Component ( { templateUrl : './object-link-add-modal.component.html' , styleUrls : [ './object-link-add-modal.component.scss' ] } ) export class ObjectLinkAddModalComponent implements OnInit , OnDestroy { private subscriber : ReplaySubject < void > = new ReplaySubject < void > ( ) ; public primaryResult : RenderResult ; @ Input ( 'primaryResult' ) public set primaryRenderResult ( result ) { this . primaryResult = result ; this . form . get ( 'primary' ) . setValue ( this . primaryResult . object_information . object_id ) ; } public form : FormGroup ; private sameIDValidator ( ) { return ( control ) : { [ key ] : any ; } | null => { const same = control . value === this . primary . value ; return same ? { sameID : { value : control . value } } : null ; } ; } constructor ( public activeModal , private objectService ) { this . form = new FormGroup ( { primary : new FormControl ( null , [ Validators . required ] ) , secondary : new FormControl ( '' , [ Validators . required , this . sameIDValidator ] , [ checkObjectExistsValidator ( objectService ) ] ) } ) ; } public get primary ( ) : FormControl { return this . form . get ( 'primary' ) as FormControl ; } public get secondary ( ) : FormControl { return this . form . get ( 'secondary' ) as FormControl ; } public ngOnInit ( ) { this . form . get ( 'secondary' ) . updateValueAndValidity ( ) ; } public async onSave ( ) { const formData = this . form . getRawValue ( ) ; this . activeModal . close ( formData ) ; } public ngOnDestroy ( ) { this . subscriber . next ( ) ; this . subscriber . complete ( ) ; } }