Tips for Successfully Transmitting Information via Mat-Dialog

Having trouble passing data from a dialog back to the parent component. Specifically, I'm struggling with updating the value of an array in the `afterClosed` function. I've tried using `patchValue` and `setValue`, but it doesn't seem to be working. Can anyone offer some guidance?

MAT DIALOG

OnInit(): void {
    this.fg = this.fb.group({
      id: [],
      qty: [],
      displayArray: this.fb.array([this.CreateItem()]),
    });
    this.fg.get('qty').valueChanges.subscribe((res) => {
      for (let i = this.displayArray.length; i < res; i++) {
        this.displayArray.push(this.CreateItem());
      }
    });
    this.data = this.fg.get('qty').setValue(this.data.qty);
  }

  CreateItem(): FormGroup {
    return this.fb.group({
      MoreItem: [''],
    });
  }
  get displayArray(): FormArray {
    return this.fg.get('displayArray') as FormArray;
  }
  inMemoryList() {
    this.http.get<MyDTO>('api/users').subscribe((test) => (this.myDTO = test));
  }
  save() {
    this.dialogRef.close([this.data.qty]);
  }

MY PARENT COMPONENT

  CreatesetItem(): FormGroup {
    return this.fb.group({
      ListItem: [''],
    });
  }
  item(): FormGroup {
    return this.fb.group({
      qty: [],
      name: [''],
    });
  }
  get setItem(): FormArray {
    return this.fg.get('setItem') as FormArray;
  }
  get Info(): FormArray {
    return this.fg.get('Info') as FormArray;
  }
  openAlertDialog(index: number) {
    const dialogRef = this.dialog.open(AlertDialogComponent, {
      data: {
        qty: this.fg.value.Info[index].qty,
        name: this.fg.value.Info[index].name,
      },
    });
    dialogRef.afterClosed().subscribe((result) => {
      for (let i = 0; i < result; i++) {
        this.setItem.push(this.CreatesetItem());
      }
      for (let i = 0; i < result; i++) {
        this.setItem.at(i).patchValue({ qty: result.qty });
      }
    });
  }

Answer №1

Modify the dropdown selection to trigger a change event and then fill in the empty input boxes with the selected values using [(ngModel)]="variable"

app.html

<select (change)="setSelectedItem($event)"> 
  <option>option1</option>
  <option>option2</option> 
</select>

<input type="text" [(ngModel)]="field1" name="field1">
<input type="text" [(ngModel)]="field2" name="field2">

app.component.ts

// initialize variables
field1: string;
field2: string;

// function triggered by dropdown change

setSelectedItem(event) {
  
  // assign selected values to variables
  this.field1 = "Hi";
  this.field2 = "Hello";

}

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

Implement validation within the child component using Reactive Forms

In this demonstration, a reactive form has been created with an input field placed inside a child component. The goal is to add a new form control within the child component and perform validation on it within the same component. However, an error has been ...

Guide to successfully submitting an Angular form that includes a nested component

I have developed a custom dateTime component for my application. I am currently facing an issue where I need to integrate this component within a formGroup in a separate component. Despite several attempts, I am unable to display the data from the child fo ...

Issues discovered with using Typescript in Visual Studio 2015

I'm having trouble figuring out the issue. Right now, the typescript file is not appearing correctly in Visual Studio 2015. Take a look at the image linked here: https://i.stack.imgur.com/oXXWD.png ...

Ways to mandate a field to only be of type object in TypeScript

I need to design a type that includes one mandatory property and allows for any additional properties. For instance, I require all objects to have an _id property of type string. {_id: "123"} // This will meet the criteria {a: 1} // This will not work as i ...

How can jsPDF be used with Angular2 in Typescript?

Recently, I developed an Angular2 application that is capable of generating JSON data. My main goal was to store this JSON output into a file, specifically a PDF file. This project was built using Typescript. To achieve the functionality of writing JSON d ...

The ins and outs of implementing i18n on an Angular component library

My custom component library is not functioning properly with i18n within my module // To enable Ahead-of-Time compilation, a function must be exported for factories export function HttpLoaderFactory(http: HttpClient) { return new TranslateHttpLoader(ht ...

Attempting to map an object, however it is showing an error stating that the property 'title' does not exist on type 'never'

While attempting to retrieve data from the Bloomberg API, I encountered an issue when trying to extract the title from the response object. The error message received was: Property 'title' does not exist on type 'never'. Below is the co ...

The debate between using backticks and colons in TypeORM queries

Lately, I've been crafting queries utilizing backticks const firstUser = await connection .getRepository(User) .createQueryBuilder("user") .where(`user.id = '${id}'`) .getOne(); However, in the typeorm documentatio ...

Align the ion content (or text or label) to the center vertically

I am striving to achieve a similar look as shown in the following images: https://i.sstatic.net/YFMay.png However, I am currently at this stage: https://i.sstatic.net/ZvpBV.png Please note that the first image showcases a bootstrap form, while the seco ...

Encountering a Angular 12 Observable<Object[]> Error while attempting to execute a GET request

I've been grappling with this error I encountered while working on Angular 12. Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays. This is the code f ...

Angular 17 doesn't seem to be correctly implementing *ngIf to hide the div

After spending hours trying to display a div based on certain conditions using *ngIf in Angular, I am still unable to make it work. The following code is not showing the expected result: <div *ngIf="item.billingItem=='Staff'">This ...

Is there a way to extract various pieces of data from a single object and implement them in a NextJs 13 application directory?

My Django RESTapi is providing output data in the following format: { "count": 1000, "next": "http://127.0.0.1:8000/store/products/?page=2", "previous": null, "results": [ { "id": 648, ...

Is the AngularJS email validation triggering too soon?

My challenge involves validating an email field in angularjs using the following code: <input type="email" ng-model="email" class="form-control" name="email" ng-required="true" placeholder="Email Address"> <span ng-show="loginForm.email.$touched ...

Navigating through a large array list that contains both arrays and objects in Typescript:

I have an array containing arrays of objects, each with at least 10 properties. My goal is to extract and store only the ids of these objects in the same order. Here is the code I have written for this task: Here is the structure of my data: organisationC ...

Angular Screen Capture Creator

I am currently in the process of constructing a straightforward Angular screenshot generator utilizing this specific jQuery plugin. Here is the link to my project on Plunker This snippet showcases my index.html file: <!DOCTYPE html> <html ng-ap ...

HTML code featuring an Angular controller's scope

Within my controller, I have the following code: (function () { 'use strict'; var LoginController = function($scope, $http, $timeout,$location,User) { $scope.user = {}; $scope.flags = { error: false, rememberMe: true ...

Exploring the Scope of a Directive within an HTML Element's Event Handler

I devised a custom Directive for utilizing an element as a 'dropzone' with native HTML Drag & Drop functionality. Custom Directive Source Code import { Directive, ElementRef, OnInit, Output, EventEmitter, ViewChild } from '@angular/co ...

When a child triggers a non-bubbling event, the view reference in Angular 2 structural directive is automatically cleared

Imagine we have a set of images that need to be displayed: <div *ngFor="let image of images; let i = index"> <div *appMaskImageOnError="i" #mydir> <img [src]="image" alt="" (error)="mydir.remove()"> </div> < ...

Unable to access due to CORS policy restriction in Ionic 5 Angular platform

Encountering an error, seeking guidance on the issue. Configuration has been done in proxy.conf.json. Headers with base url have been set in user.service.ts. import { Injectable } from '@angular/core'; import { Http, Headers, RequestOptions } fr ...

What are some strategies I can implement to effectively manage different errors and ensure the app does not crash

I came across a variety of solutions for error handling. The key concept revolves around this explanation: https://angular.io/api/core/ErrorHandler Attempts were made to implement it in order to capture TypeError, however, the outcome was not successful: ...