Adding a component to a page in Angular 4: A step-by-step guide

Currently engaged in a project that involves creating a mobile application design within a web application.

I'm wondering how to display my Component object on a page using ViewChild?

I have a list of PageComponents, below is the PageComponent class:

export class PageComponent implements OnInit {

  pageName : string;
  components: Array<BaseComponentComponent>[]

  constructor() { 
  }

  public setPageName(name: string) {
    this.pageName = name;
  }

  public getPageName() {
    return this.pageName;
  }
}

HTML content of PageComponent:

<p>
  {{pageName}}
</p>

Nothing out of the ordinary so far, but I want to open the clicked PageComponent from the list.

I attempted to use ComponentFactoryResolver for this purpose, however, it creates a new instance of PageComponent which wasn't helpful.

openPage(page: PageComponent) {
    let test = this.cfr.resolveComponentFactory(page);
    this.parent.clear();

    let componentRef = this.parent.createComponent(test);
}

Is there a way to display the Component object directly onto a page?

Answer №1

To access a ViewChild from the parent view, you can utilize the following method:

<div #container></div>

Next, make sure to reference it in your component code:

@ViewChild('container', {read: ViewContainerRef}) container: ViewContainerRef;

Finally, you can insert your component once everything is configured correctly:

this.container.insert(this.component.hostView);

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

Can a standard tuple be matched with its corresponding key?

This code snippet showcases a function that can recognize that the key "banana" cannot have the value "red": type Fruits = { banana: 'yellow' | 'green' strawberry: 'red' } const fruit = <K extends keyof Fruits>(modu ...

employing a variable within a function that is nested within another function

I'm encountering an issue where I am using a variable within a nested function. After assigning a value to it, I pass it to the parent function. However, when I call the function, nothing is displayed. function checkUserExists(identifier) { let user ...

Harvesting Angular information using Selenium

Here is some HTML code that can be extracted using a Selenium driver: <td colspan="2"><strong>Owner</strong> <div ng-class="{'owner-overflow' : property.ownersInfo.length > 4}"> ...

The issue of resolving NestJs ParseEnumPipe

I'm currently using the NestJs framework (which I absolutely adore) and I need to validate incoming data against an Enum in Typscript. Here's what I have: enum ProductAction { PURCHASE = 'PURCHASE', } @Patch('products/:uuid&apos ...

Angular: The specified function name cannot be called

My approach involves assigning an imported function to a component property within the constructor so that it can be utilized in the template. Although builds are successful, an error appears in my editor (Visual Studio Code with Angular Language Service) ...

Is the ID sent upon selection change?

<select class="form-control" type="text" required (change)="onChangeLov($event)">> <option value=""></option> <option *ngFor ="let contact of contacts">{{contact.id}} - {{contact.name}}, {{contact.ptechnologyName}}, ...

How do you transfer byte[] data using a DTO in Java Spring?

I am currently facing an issue with my server-side application. The problem arises when attempting to convert a Blob to an Excel file on the front-end, specifically when the byte[] is sent within a DTO. When sending a POST request from the back-end (sprin ...

Enforcement of static methods in Typescript abstract classes is not mandatory

In my TypeScript code, I have a simple structure defined: abstract class Config { readonly NAME: string; readonly TITLE: string; static CoreInterface: () => any } class Test implements Config { readonly NAME: string; readonly TITL ...

Integrate the use of `Refresh Token` into an `Angular` application

In my current project, I am tackling the integration of Spring Security with OAuth2 and JWT: The author suggests that I can access resources using a token in the following manner: To access a resource, use the following command (assuming you have config ...

Is there a way to verify the presence of data and halt code execution if it is not found?

In my data, there is a table containing a total of 5 links. The first 2 links can vary in availability as they are dynamic, while the last 3 links are static and are always displayed. The dynamic links' data is deeply nested within the state object, s ...

Please provide either a string or an object containing the proper key for TypeScript

Within my project, the languageSchema variable can either be a string or an object containing the 'Etc' key. The corresponding interface is defined as follows: let getLanguageSchema = (language: string): string => languagesSchemas[language]; ...

Alert: Zone.js has identified that the ZoneAwarePromise '(window|global).Promise' has been replaced with polyfills. Kindly address this issue

Recently, I updated my Angular application from version 8 to 9. After updating the packages and successfully compiling the application, I encountered an error message in the Chrome browser console: Error: Zone.js has detected that ZoneAwarePromise `(wind ...

Angular: Modifying a Component Property Value within an ngFor Loop

Within an ngFor loop, I have a tabs component. To apply a CSS class, I utilize the boolean property show, which is initially set to false. When I click on the component, the value of show toggles to true. However, if I click on another component, I need to ...

NgbHighlight now allows for one highlight element per line

I am currently utilizing NgbHighlight to allow users to search within a list. However, I am facing an issue with the highlighting of search results. My intention is to highlight only the first match in the list. I am sticking to the basic implementation ...

What is the best way to incorporate padding into an Angular mat tooltip?

I've been attempting to enhance the appearance of the tooltip dialog window by adding padding. While adjusting the width and background color was successful, I'm encountering difficulties when it comes to styling the padding: https://i.sstatic.ne ...

What is the most effective method to create a versatile function in Angular that can modify the values of numerous ngModel bindings simultaneously?

After working with Angular for a few weeks, I came across a problem that has me stumped. On a page, I have a list of about 100 button inputs, each representing a different value in my database. I've linked these inputs to models as shown in this snipp ...

Is it possible to modify a portion of the zod schema object according to the value of a

My form consists of several fields and a switch component that toggles the visibility of certain parts of the form, as shown below: <Field name="field1" value={value1} /> <Field name="field2" value={value2} /> &l ...

Tips for modifying the data type of a property when it is retrieved from a function

Currently, I have a function called useGetAuthorizationWrapper() that returns data in the format of { data: unknown }. However, I actually need this data to be returned as an array. Due to the unknown type of the data, when I try to use data.length, I enc ...

Find keys in an array based on a specified value

I need to retrieve an array of keys from an object that match a specified value ...

Tips on organizing a typescript object/StringMap in reverse order to prioritize the last element

I've just started working with TS/React in a .tsx file and I'm trying to add a key/value pair to a StringMap at the very first index. Below is the code snippet that: takes the StringMap 'stats' as input, iterates through each row, re ...