Passing input data to ng-content component in Angular

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

Answer №1

To handle formData in a more organized way, you can store it as a property of a service and then retrieve it in the content component's ngOnInit(). I have tested the following code and it works successfully for me.

 @Injectable()
    export class ModalService {
      dialogComponentRef: ComponentRef<ModalComponent>;
      formData:any;
      private subject = new Subject<any>();
    
      open(content: any, obj: any) {
       this.formData = obj;
        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);
      }
    }

Then, in the ngOnInit() of the content-component:

ngOnInit() {
   this.name = this.modalService.formData.name;
}

You may consider encapsulating this property within a function inside the service, rather than accessing it directly (e.g., getFormData()).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Every time the page is loaded, the drop-down list of products is assigned a unique ID

Currently, I am utilizing Selenium IDE for repetitive form filling tasks on a web application. One of the steps involves selecting a set of products and subsequently choosing specific base products from that selection. For instance, I need to filter all pa ...

Problem with the document.form in Javascript

I've encountered an issue while running the code and I'm having trouble figuring out what's causing it. The code was running fine before, but now I'm facing this problem: function makeUnderline(formName,editor) { var txt = window.p ...

Unable to launch ionic3 application on localhost using ionic serve, resulting in a blank page

https://i.sstatic.net/Mu04d.jpg Hey everyone, I've been working on this app for the past 2 months and it's something completely new. Today when I ran 'ionic serve' command, all I got was a blank page. I tried multiple times but nothing ...

Passing a variable via routes using Express

app.js var express = require('express'); var app = express(); var textVariable = "Hello World"; var homeRoute = require('./routes/index'); app.use('/', homeRoute); index.js var express = require('express'); var ...

Unexpected token < error encountered during parsing in jQuery Ajax long polling append

How can I create a real-time ticker similar to Facebook using Jquery Ajax long poll and PHP? I encountered an error in my script that displays "error parsererror (SyntaxError: Unexpected token <)". What could be causing this error in my code? Here is ...

Issue: Unable to resolve all parameters for LoginComponent while implementing Nebular OAuth2Description: An error has occurred when attempting to

I have been attempting to utilize nebular oauth in my login component, following the documentation closely. The only difference is that I am extending the nebular login component. However, when implementing this code, I encounter an error. export class Lo ...

jQuery - Issue arises when no radio button is selected

Currently, I am working with a group of radio buttons and need to implement validation that shows an error message if none of the buttons are checked. Is there a method to retrieve the combined value of all radio buttons at once, or will I have to indivi ...

Creating movement for a shape using the keyIsDown function in p5.js

Having some trouble with p5.js and trying to make a shape move on the canvas. However, instead of smoothly moving the shape, it's leaving a trail behind as it redraws in the new position. Not quite the effect I was going for. Take a look at the issue ...

Strategies for capturing unhashed routes through the use of a hashed location strategy

I can't seem to figure this out. Our application is using HashLocationStrategy, which we need to keep in some cases. However, I need to detect specific paths that contain a series of numbers like this: www.someurl.com/1241234 I've created an Ang ...

Error message received when attempting to insert a product using the Google Shopping API in node.js: "INSERT request must specify product"

I've been attempting to add a product to the Google Shopping API using this node.js code, but I've been encountering an error: { [Error: [product] INSERT request must specify product] code: 400, errors: [ { domain: 'global', reason: ...

make the text in em font size larger

Incorporating HTML dynamically into a page using JavaScript is shown in the example below. _strInnerHtml += "<em>" + value.cate_name + " | " + value.city_name + "</em>"; _strInnerHtml += "<a href='#' class='activi ...

What is the best way to execute a series of asynchronous JavaScript functions one after the other?

As I attempt to call the following functions in succession, their return does not always happen in the expected order. Upon discovering asynchronous functions and the concept of using "callbacks," I realized there might be a solution for executing these f ...

What is the best way to integrate Bootstrap v4 into the most recent version of Angular?

npm install --save bootstrap I find the new version of Bootstrap to be less user-friendly compared to v4. Is there a way to install a specific older version of Bootstrap in an Angular project without getting the latest one? ...

Using jQuery to load the center HTML element

So here's the plan: I wanted to create a simple static website with responsive images that load based on the browser width. I followed some suggestions from this link, but unfortunately, it didn't work for me. I tried all the answers and even a ...

How can you resolve the error message "No overload matches this call." while implementing passport.serializeUser()?

Currently, I am working on implementing passport.serializeUser using TypeScript. passport.serializeUser((user: User, done) => { done(null, user.id) }); The issue I am encountering is as follows: No overload matches this call. Overload 1 of 2, &ap ...

The issue with triggering button events in JavaScript

I've integrated a jquery modal popup for saving uploaded files related to a specific device. The modal appears, the cancel button functions correctly, but I am struggling to trigger the onclick event for the Save button... This is what I have impleme ...

Solving complex promises in both serial and parallel fashion

My current function performs four tasks that must be executed in a specific sequence: - promise1 - promiseAfter1 // In parallel - promise2 - promiseAfter2 To ensure the promises are handled sequentially, I have structured two separate functions as follows ...

Maximizing the use of ng-bootstrap collapse components on a single page

How can I implement the collapse component from this resource on my page multiple times without having all of them collapse when just one is clicked? I only want the specific one that is clicked to collapse. ...

Can the code be altered to toggle the button's enable/disable state without the need to refresh the page?

Is there a way to change the disable/enable status of a button without needing to refresh the page? The current code works, but requires a page refresh to reflect the changes. The page displays more than 30 products with buttons created using the same code ...

The Spring controller receives only the initial index of the stringified array from Ajax

Below is the complete JS code snippet: function getPoolsData(){ $.getJSON('../json/data.json', function(data) { var date_from = new Date(); console.log(date_from); var pools_hashrates = [{"date_from" : date_from}]; data.pools.forEach(function( ...