I am working on a modal component that utilizes ng-content. Within this ng-content, I am able to pass other components with an injector. However, I am facing a challenge in passing an object for data editing. Here is the HTML code for the modal component:
<div class="modal">
<div class="modal-body">
this is my Object: {{model | json}}
<ng-content></ng-content>
</div>
<div class="modal-footer">
<button (click)="sendMessage()">success</button>
<button>abort</button>
</div>
</div>
The components within the ng-content can vary. In my example, I have an input element. I need to pass a model into these components.
To achieve this, I am using a service with an injector to pass content into my ModalComponent. The "open" function of the service includes a parameter called obj which represents the object needed inside the ng-content component (stored in the "model" input of the Modal component).
@Injectable()
export class ModalService {
dialogComponentRef: ComponentRef<ModalComponent>;
private subject = new Subject<any>();
open(content: any, obj: any) {
const contentComponentFactory = this.cfResolver.resolveComponentFactory(content);
const modalComponentFactory = this.cfResolver.resolveComponentFactory(ModalComponent);
const contentComponent = contentComponentFactory.create(this.injector);
const modalComponent = modalComponentFactory.create(this.injector, [[contentComponent.location.nativeElement]]);
modalComponent.instance.model = obj;
this.dialogComponentRef = modalComponent;
document.body.appendChild(modalComponent.location.nativeElement);
this.appRef.attachView(contentComponent.hostView);
this.appRef.attachView(modalComponent.hostView);
}
}
This is my ModalComponent Class:
export class ModalComponent {
@Input() model: any;
sendMessage() {
this.modalService.sendMessage();
}
constructor(private modalService: ModalService) {}
}
Hence, I have created a component with the following HTML:
<input type="text" value="name" placeholder="name">
Within this input, I aim to display the object for editing its value.
I am currently seeking a solution to have the object inside the content-component as I require it for editing values in a form.
You can find my StackBlitz example here: Example