One of my challenges involves dynamically adding different components when the user clicks, allowing them to add and remove any component. However, I am struggling to figure out how to reference the component where the user clicked in Angular-4.
here are some sample components that are loaded in app.component.ts
:
@Component({
selector: 'question-paragraph',
template: `<div class="form-group container">
<textarea></textarea>
</div>`,
})
export class QuestionParagraphComponent { }
@Component({
selector: 'question-image',
template: `<div class="form-group container">
<form enctype="multipart/form-data" action="" method="post">
<p>Upload Image</p>
<input type="file" name="uploaded_file[]" />
</form>
</div>`,
})
export class QuestionImageComponent { }
Below is the function that adds these components:
if (item=='question') {
this.addService.appendComponentToBody(QuestionDetailComponent);
this.removeComponent(this.sg[this.sg['question_id']]);
} else if (item=='image') {
this.addService.appendComponentToBody(QuestionImageComponent);
this.removeComponent(this.sg[this.sg['question_id']]);
let componentRef = this.addService.appendComponentToBody(QuestionTypeComponent);
this.sg['ComRef'] = componentRef;
}
I have a function to remove the component, but it requires knowing the component's reference:
removeComponent(componentRef){
this.appRef.detachView(componentRef.hostView);
componentRef.destroy();
}
If anyone knows how to get the reference of a component on click, I would greatly appreciate your help. Thank you.