import { Component , Input , OnDestroy , OnInit } from '@angular/core' ; import { BehaviorSubject , ReplaySubject } from 'rxjs' ; import { takeUntil } from 'rxjs/operators' ; import { AbstractControl , FormControl , FormGroup } from '@angular/forms' ; @ Component ( { selector : 'cmdb-object-bulk-input-appends' , templateUrl : './object-bulk-input-appends.component.html' , styleUrls : [ './object-bulk-input-appends.component.scss' ] } ) export class ObjectBulkInputAppendsComponent implements OnInit , OnDestroy { private subscriber : ReplaySubject < void > = new ReplaySubject < void > ( ) ; @ Input ( ) public changeForm : FormGroup ; @ Input ( ) public controller : FormControl ; @ Input ( ) public data : any ; public checkedSubject : BehaviorSubject < boolean > = new BehaviorSubject < boolean > ( false ) ; public ngOnInit ( ) { this . controller . valueChanges . pipe ( takeUntil ( this . subscriber ) ) . subscribe ( ( ) => { if ( ! this . checked ) { this . checkedSubject . next ( true ) ; } this . changeForm . get ( this . data . name ) . setValue ( this . controller . value ) ; } ) ; this . checkedSubject . asObservable ( ) . pipe ( takeUntil ( this . subscriber ) ) . subscribe ( ( checked ) => { this . changeCheckBox ( checked ) ; } ) ; } public get checked ( ) : boolean { return this . checkedSubject . value ; } public changeCheckBox ( checked ) { if ( checked ) { this . changeForm . addControl ( this . data . name , new FormControl ( this . controller . value ) ) ; } else { this . changeForm . removeControl ( this . data . name ) ; } } public onCheckChange ( event ) { this . checkedSubject . next ( ( event . target as HTMLInputElement ) . checked ) ; } public ngOnDestroy ( ) { this . subscriber . next ( ) ; this . subscriber . complete ( ) ; } }