Learn how to bring a component into another component within Angular

I have developed a component named CopySchedulefromSiteComponent and now I am looking to import it into another component called SiteScheduleComponent. However, I am unsure of the correct way to do this.

The CopySchedulefromSiteComponent contains one field utilizing Formly

CopySchedulefromSiteComponent

 @Component({
  selector: 'app-copy-schedule-from-site',
  templateUrl: './copy-schedule-from-site.component.html',
  styleUrls: ['./copy-schedule-from-site.component.scss'],
  })
export class CopyScheduleFromSiteComponent implements OnInit {
showOverwriteWarningModal(): Observable<boolean> {
const deleteRef = this.dialog.open(CopyScheduleModalComponent, {});
return deleteRef.afterClosed();
}

  copySiteScheduleControl: FormlyFieldConfig | undefined;

 modelLoaded = false;
 form = new FormGroup({});
 options: FormlyFormOptions = {};
 fields: FormlyFieldConfig[] = [
  {
   fieldGroupClassName: 'row',
   fieldGroup: [
    {
      wrappers: ['form-field'],
      className: 'col-6',
      key: 'siteScheduleControl',
      type: 'select',
      templateOptions: {
        label: 'Copy Schedule from Site',
        options: this.approvedSites,
        labelProp: 'text',
      },
      expressionProperties: {
        'templateOptions.disabled': (): boolean => {
          return this.siteSubmissionModel.disableControls;
        },
      },
      hooks: {
        onInit: (field: FormlyFieldConfig | undefined): void => {
          this.copySiteScheduleControl = field;
          if (field?.templateOptions?.options) {
            field.templateOptions.options = this.approvedSites;
          }
        },
      },
      },
    ],
  },
];

I aim to connect/import the formly field from CopySchedulefromSite component to the formly fields in SiteScheduleComponent after importing the component. However, I receive an error stating ''CopyScheduleFromSiteComponent' is declared but its value is never read'. Below are some formly fields included

SiteScheduleComponent

 import {CopyScheduleFromSiteComponent} from './copy-schedule-from- 
   site/copy-schedule-from-site.component';

 @Component({
 selector: 'app-site-schedule',
 templateUrl: './site-schedule.component.html',
 styleUrls: ['./site-schedule.component.scss'],
 })
export class SiteScheduleComponent implements OnInit, OnChanges {
@Input() siteSubmissionModel: SiteSubmissionModel = new SiteSubmissionModel();    

  copySiteScheduleControl: FormlyFieldConfig | undefined;
  model: SiteScheduleModel = {
  siteScheduleControl: undefined,
   monthsOfOperation: new CoreApi.MonthsOfOperation(),
   daysOfOperation: {days: []},
   hoursOfOperation: {days: []},
   exception: [],
 };
  modelLoaded = false;
  form = new FormGroup({});
  options: FormlyFormOptions = {};
  fields: FormlyFieldConfig[] = [
  {
   fieldGroupClassName: 'row',
  fieldGroup: [
    {
      wrappers: ['form-field'],
      className: 'col-6 mt-small',
      type: 'button',
      templateOptions: {
        text: 'Copy',
        matIcon: 'file_copy',
        onClick: (): void => {
          if (this.model.monthsOfOperation && (this.model.monthsOfOperation.fromDate || 
             this.model.monthsOfOperation.toDate)) {
            this.showOverwriteWarningModal().subscribe((confirmed) => {
              if (confirmed) {
                this.copySchedule();
              }
            });
          } else {
            this.copySchedule();
          }
        },
      },
      expressionProperties: {
        'templateOptions.disabled': (): boolean => {
          return !this.model.siteScheduleControl || this.siteSubmissionModel.disableControls;
        },
      },
    },
    ],
   },
   {
  template: '<h4>Months of Operation</h4>',
   },
   {
    fieldGroupClassName: 'row',
    fieldGroup: [
     {
      className,
      fieldGroup: [
        {
          key: 'monthsOfOperation',
          type: FORMLY_CUSTOM_TYPE_DATE_RANGE_PICKER,
          templateOptions: {
            fromDate: 'monthsOfOperation.fromDate',
            toDate: 'monthsOfOperation.toDate',
            required: true,
            onDateChange: (): void => this.onMonthsOfOperationChanged(),
          },
          expressionProperties: {
            'templateOptions.disabled': (): boolean => {
              return this.siteSubmissionModel.disableControls;
            },
          },
         },
        ],
      },

Please provide guidance on resolving this issue.

Answer №1

If you wish to include one Component within another, the best practice is to nest them rather than importing one into the other.

In order to use Component A inside Component B, make sure they are either both declared in the same Module or import Component A into the Module where Component B is defined.

Once this condition is satisfied, you can insert Component A's selector into the html of Component B to utilize it. Communication between the Components can then be facilitated through Inputs and Outputs.

For further information on Components and Modules:

https://angular.io/api/core/Component

https://angular.io/guide/architecture-modules

To gain a solid understanding of utilizing Components:

https://angular.io/tutorial/toh-pt3

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

Validation parameters provided during the Palantir workshop

At our Palantir workshop, we utilize a form to input values that are then added to an Ontology object. Recently, I've been tasked with validating the combination of userId, startdate, and states from the form inputs to check if they already exist or n ...

Discovering the ASP.NET Core HTTP response header in an Angular application using an HTTP interceptor

I attempted to create a straightforward app version check system by sending the current server version to the client in the HTTP header. If there's a newer version available, it should trigger a notification for the user to reload the application. Ini ...

What is the best way to present sorted items on a user interface?

I have a unique Med interface containing properties like drugClass, dosage, and name. Using this interface, I created an array of drugs with different attributes. How can I filter this array by drugClass and then display the filtered data on a web page? ...

Encountering issues with @typescript-eslint/typescript-estree due to using a non-officially supported version of TypeScript after updating Nuxt

After upgrading Nuxt in my project using the command npx nuxi upgrade, I encountered an issue while running eslint .. The output displayed a warning regarding the TypeScript version: ============= WARNING: You are currently running a version of TypeScript ...

Solving Angular2 Dependency Issues

I'm curious about Angular 2 and whether there's a way to resolve dependencies without having to use the constructor. In .NET, you can inject dependencies in three ways (constructor, setter, interface-based). Is it possible to do setter injection ...

When using Angular 5's ngModel, the user interface displays the updated value dynamically without requiring the

When filling out my form, I encounter an issue with a select element and a bind variable. If I make a change to the value and save it, everything works as expected. However, if I make a change in a modal window but then close the modal without saving the v ...

Node corrupting images during upload

I've been facing an issue with corrupted images when uploading them via Next.js API routes using Formidable. When submitting a form from my React component, I'm utilizing the following functions: const fileUpload = async (file: File) => ...

The inner workings of Angular 2: uncovering what occurs once we navigate to http://localhost:4200 on our browser

Could anyone provide a detailed explanation of the startup process for an Angular2 project? For example, after creating a sample project using Angular CLI: Run 'ng new my-test-app' Navigate to 'cd my-test-app' Start the server with & ...

Set Chartjs2 data to display as a doughnut chart starting from 0

When working with a doughnut chart and having data values set to 0, it is important to ensure that the default chart still displays with equal size parts. To achieve this, one can utilize the beginAtZero option in JavaScript: JS scales: { yAxes: [{ ...

Issue with locating image source in Angular 4

I'm struggling to source an image using angular 4. It keeps giving me an error message saying that the image cannot be found. Here is my folder structure: app_folder/ app_component/ - my_componenet - image_folder/ - myimage I am trying to ...

The shop named 'someStore' is currently unavailable! Please ensure that it is being offered by a valid Provider

I'm having trouble setting up a new project using React, Typescript, and MobX. Despite having a relatively simple piece of code, I can't seem to get MobX to work properly. It keeps showing me this error message: Uncaught Error: MobX injector: S ...

Making all requests server-side in Next.JS: A step-by-step guide

I am in the process of creating a Next.JS application that will be retrieving data from both a Python API and a Postgres Database. Although this task may seem straightforward, the project requirements dictate that all requests must originate from the serv ...

The React Hook Form's useFieldArray feature is causing conflicts with my custom id assignments

My schema includes an id property, but when I implement useFieldArray, it automatically overrides that id. I'm utilizing shadcn-ui Version of react-hook-form: 7.45.0 const { fields, append, remove, update } = useFieldArray<{ id?: string, test?: n ...

Detecting property changes in Angular 2: A step-by-step guide

I've created a basic class structure like so: export class MessagesPage { @ViewChild(Content) content: Content; public message = ''; public messages = []; public state = 'general'; } Can I implement a way wit ...

React Native component that enables users to both input their own text and select options from a dropdown menu as they type

Looking to develop a component that combines Text Input and FlatList to capture user input from both manual entry and a dropdown list. Has anyone successfully created a similar setup? I'm facing challenges in making it happen. Here's the scenari ...

Changing the ngModel value within ngFor loop

I am working on a project where I need to display a list of grades from an object called 'grades'. Additionally, I want to integrate a slider component for each grade, with the value of the slider corresponding to a predefined list. However, it s ...

Is there an alternative method to incorporate the 'environment.ts' file into a JSON file?

In my Angular application, I need to import assets based on the env configuration. I am attempting to extract the patch information from environment.ts and save it into my assets as a json file. However, I am unsure of the proper method to accomplish this. ...

Learn the process of importing different types from a `.ts` file into a `.d.ts` file

In my electron project, the structure looks like this: // preload.ts import { contextBridge, ipcRenderer, IpcRendererEvent } from 'electron' import { IpcChannels } from '@shared/channelNames' contextBridge.exposeInMainWorld('api&a ...

Exploring the MVVM architecture in React and the common warning about a missing dependency in the useEffect hook

I'm currently in the process of developing a React application using a View/ViewModel architecture. In this setup, the viewModel takes on the responsibility of fetching data and providing data along with getter functions to the View. export default f ...

Is it possible to set up Injector within TestBed?

Currently, I am in the process of writing test cases for a custom ErrorHandler within Angular. In my implementation, I have included Injector as a dependency in the constructor due to the understanding that providers are initialized after ErrorHandler. The ...