I am working on a project that involves 3 TS files: 1) Parent-Component.ts 2) Child-Component.ts 3) Service.ts
In the Parent-Component.ts file, there is a button click event that calls a function in Service.ts. This function dynamically creates the Child Component using the code provided below.
Parent-Component.html:
<div class="form-group">
<div class="row">
<div class="mt-3 col-md-12">
<h3>{{ i18n.common + 'Filter' | dynamicTranslate }}</h3>
<div #filterCriteria></div>
</div>
</div>
</div>
<div class="row filter-actions mb-3">
<div class="col-md-12">
<button type="button" **(click)="appendAdditionalFilter()" **>
<i class="fa fa-plus"></i></button> <strong> {{ 'Add Filter' }}</strong>
<button type="button" class="btn btn-primary ml-2"
(click)="appendFilterFromService()">{{ i18n.common + 'Apply Filter' | dynamicTranslate }}
</button>
</div>
</div>
When the "Add Filter" button is clicked, the appendAdditionalFilter() function is called in Parent-Component.ts, which then calls Service.ts to create the child component dynamically.
Parent-Component.ts:
@ViewChild('filterCriteria', { read: ViewContainerRef, static: false})
filterCriteriaContainer: ViewContainerRef;
appendAdditionalFilter() {
this.filterCriteriaContainer = this.filterGridService
.addFilter(this.filterCriteriaContainer, this.MetaData, this.i18n.Test1,
this.Test2);
}
Service.ts:
addFilter(
filterCriteriaContainer: ViewContainerRef,
MetaData: Array<FieldMetaDataDto>,
Test1: string,
Test2?: number,
filter?: FilterDto,
): ViewContainerRef {
const comp = this.componentResolver.resolveComponentFactory(ChildComponent);
const filterCriteria = filterCriteriaContainer.createComponent(comp);
filterCriteria.instance.ref = filterCriteria;
filterCriteria.instance.translationKeyBase = Test1;
filterCriteria.instance.filterMetadata = MetaData;
filterCriteria.instance.dataTarget = Test2;
return filterCriteriaContainer;
}
There is also a "Remove" button click event in the Child Component that needs to call the appendFilterFromService() function in Parent-Component.ts.
Child-Component.html:
<div>
<button (click)="remove()" type="button" class="btn btn-action btn-small">
<i class="fa fa-minus"></i>
</button>
<strong>{{i18n.common + 'Remove Filter' | dynamicTranslate }} </strong>
</div>
Child-Component.ts:
ref: ComponentRef<ChildComponent>;
remove(){
this.ref.destroy();
//Need to call Parent-Component.ts function appendFilterFromService() here//
}
Any assistance would be greatly appreciated.