Guide on accessing a modal component in Angular?

I have an Edit Button on my component called SearchComponent. When the user clicks this button, it currently redirects them to another component named EditFormComponent using navigateByUrl('url-link'). However, I would like to enhance the user experience by keeping them on the SearchComponent page and instead opening a Modal component that contains the EditFormComponent.

To achieve this, I am utilizing Angular Material Design to create the Modal component. Despite successfully calling the EditFormComponent within the Modal, I encountered an issue where the Modal displays without loading any data from the SearchComponent. Additionally, the 'background' seems to load the EditFormComponent page separately, resulting in an empty Modal component. Here is a snippet of my code: SEARCH.COMPONENT.TS

export class DistributionFormComponent implements OnInit {
@Input() dataModal: DistributionSearchModalComponent;

ngOnInit() {
  console.log('Data received from modal', this.dataModal);
}

editDistribution(id) {
  this.router.navigateByUrl(`/registry/basic/distribution/edit/${id}`);
}

openModal(id) {
      this.dialog.open(DistributionSearchModalComponent, {
        width: '660px',
        height: '760px',
        data: {
          id: id.id,
          address: id.address,
          service: id.service,
        }
      })
 }

MODAL.COMPONENT.HTML

<div fxLayout="row wrap" fxLayout.lt-sm="column" class="pt-1 pr-1 pl-1">
    <div fxFlex="95" fxLayoutAlign="start">
        <h1 matDialogTitle>Edit</h1>
    </div>
    <div fxFlex="5" fxLayoutAlign="end">
    </div>
</div>
<div fxLayout="row wrap" fxLayout.lt-sm="column" class="pt-1 pr-1 pl-1">
    <op-distribution-form [dataModal]="dataForm"></op-distribution-form>
</div>

MODAL.COMPONENT.TS

export class DistributionSearchModalComponent implements OnInit {
    dataForm = this.data;
    providerForm: FormGroup;
    distributionForm: FormGroup;
 
    constructor(
        @Inject(MAT_DIALOG_DATA) public data: any,
        public dialogRef: MatDialogRef<DistributionSearchModalComponent>,
        public confirmService: AppConfirmService,
        public fb: FormBuilder,
    ) { }

    ngOnInit(): void {
        console.log('MODAL DATA ', this.data);
 }

FORM.COMPONENT.TS

export class DistributionFormComponent implements OnInit {
    @Input() dataModal: DistributionSearchModalComponent;
    objModal;
    searchId;

    constructor(
        private dialog: MatDialog,
        private fb: FormBuilder,
        private route: ActivatedRoute,
        private router: Router,
    ) {}

    ngOnInit() {
        this.buildItemForm();
        this.distributionForm.controls.distribuicao.valueChanges.subscribe(value => {
            this.itemsSubject$.next(value);
        });
        this.hasPermission = this.permissionsServices.hasPermission('distribution');

        console.log('Data received from modal ', this.dataModal)
        this.objModal = this.dataModal;
        console.log('modal id ', this.objModal.id)        
    }

Answer №1

If you're utilizing the modal feature, there's no longer a necessity for using navigateByUrl. Instead, simply trigger openModal when the edit button is clicked.

To ensure smooth functionality of the modal, ensure that DistributionSearchModalComponent is included in your entryComponents array within app.module.ts.

Furthermore, in your modal.component.ts file, make sure to initialize dataForm with this.data, keeping in mind that dialog data hasn't been instantiated yet in the constructor.

Please feel free to reach out if you require any further clarification!

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

Are you looking to denormalize your ngrx store and configure selectors?

I am currently dealing with a complex data structure in an ngrx project. It consists of nested parent objects with multiple levels of child objects, which are normalized on the server side. Here is an overview of my store's layout: rootObjs: { le ...

Tips for avoiding the influence of the parent div's opacity on child divs within a Primeng Carousel

I'm struggling to find a solution to stop the "opacity" effect of the parent container from affecting the child containers. In my code, I want the opacity not to impact the buttons within the elements. I have tried using "radial-gradient" for multipl ...

Exploring the capabilities of zooming on SVG elements using D3 within an Angular

I want to implement pan/zoom functionality on an SVG element. I came across a tutorial that suggested using d3.js for this purpose, you can find it here Below is the code I have tried: import { Component,AfterViewInit,OnInit } from '@angular/core&a ...

Reactive Programming: Transforming an earlier value as it moves down the pipeline

In a recent project, I encountered an interesting scenario involving the execution of multiple requests in a pipe chain. This specific case revolves around the display of images within the quill text editor. The backend returns the content in the followin ...

Implement a new functionality to a publicly accessible type without violating the pre-established agreement

I'm looking to enhance an existing exported type with a new method, without causing any disruption to the current usage in production. import * as BunyanLogger from 'bunyan'; import init from './logger'; export type Logger = Bunya ...

"Converting array into a string in TypeScript/Javascript, but unable to perform operations

After generating a string with the correct structure that includes an array, I am able to navigate through the JSON on sites like However, when attempting to access the array, it turns out that the array itself is null. Here is the scenario: Firstly, th ...

Guide on formatting the API response using a callback function in Angular development

How can I reformat my API response using a callback function and access the data within the angular subscribe method? I attempted to use mergemap but it didn't work as expected. this.http.get('https://some.com/questions.xml', {headers, res ...

Include an external JavaScript file within a component to display pictures in a web browser using Angular 2

I am developing a website using Angular 2 and need to incorporate a JavaScript file into a component. The goal is for this script to adjust the height of certain images to match the height of the browser window. What is the best way to integrate this scri ...

Zod combinator that accepts a dynamic field name

When converting XML to JSON, my library outputs {MyKey: T} for single-element lists and {MyKey: T[]} for multi-element lists. The equivalent TypeScript type is type XmlJsonArray<T, element extends string> = Record<element, T | T[]>. To implemen ...

Implementing type inference for response.locals in Express with TypeScript

I need to define types for my response.locals in order to add data to the request-response cycle. This is what I attempted: // ./types/express/index.d.ts declare global { declare namespace Express { interface Response { locals: { ...

What steps should I follow to implement Cypress in an older project?

Looking to automate a project built with Node.js version 8.9.4 and an older version of Angular using Cypress for testing, but running into compatibility issues with the current version of Cypress. Is there a way to use an older version of Cypress in this ...

Transferring information to a complex and deeply embedded Angular component

In my current component structure, A includes B, B includes C, and C includes D. I am looking to transfer data from the topmost component (A) to the one at the bottom of the hierarchy (D). Should I utilize data binding in HTML templates, which would requ ...

Incorporating DevExtreme into an Angular application

After following the suggested command to add DevExtreme to my angular project using npx -p devextreme-cli devextreme add devextreme-angular, I encountered an issue related to node-modules/sass/embedded or a self-signed certificate problem. Despite trying s ...

Using TypeScript with Vue and Pinia to access the store

Is it necessary to type the Store when importing it to TypeScript in a Pinia Vue project? // Component <p>{{ storeForm.firstName }}</p> // receiving an error "Property 'storeForm' does not exist on type" // Store ...

Can the month dropdown in react-datepicker be modified to display numbers instead of names?

Here is the code I have: <DatePicker selected={value?.toDate()} onChange={(date) => this.handleMonthChange(date)} inline showMonthYearPicker dateFormat={this.props.formatString} /> I am seeking to modify it so that instead of d ...

Angular navigation system featuring hierarchical categories

My goal is to organize categories in a nest structure, but without setting a predetermined limit on the number of levels. Depending on various factors, there could be anywhere from 3 to 5 levels. For example, level 1 could be "categoryX/1", level 2 "categ ...

How to Retrieve Properties from Child Elements in NativeScript ngFor Directive

Working with a dynamically generated checklist in Angular/Nativescript: <StackLayout *ngIf="assessment"> <StackLayout *ngFor="let instance_item of assessment.exam_instance_items; let i= index"> <ns-examitem [attr.id] ...

Attach a click event to the button with a defined class using Angular

In order to meet the requirement, I need to track user click events on all buttons with a specific class. To do this, I have to bind the click event to all buttons and ensure that the same function is triggered in all components. Any ideas on how I can ac ...

Synchronization problem encountered in an Angular app involving playwright

Currently, I am working on automating a process where the service queries the database and displays the data on the user interface. However, the rendering takes a considerable amount of time, around 3 minutes. Despite using Playwright for automation, it do ...

What is the proper way to arrange dates within strings in Angular?

I'm currently facing an issue with sorting two strings. The strings in question are: "2022 | Dec (V2 2022)" "2022 | Jul (V1 2022)" Although I am attempting to sort them using localeCompare, it is not yielding the correct result. T ...