What is the best way to set a value for an undeclared control in a reactive form?

I have not declared an email control in the HTML file, but I have declared it in my form group. I want to set the email value that is receiving in the customers to the email control.

<form class="form-row" [formGroup]="form">
      <div class="col-md-3">
        <label>Email Report</label>
          <mat-radio-group class="mb-3 d-block" formControlName="emailReport" (change)="emailReport = $event.value; emitDataAndValidity()">
              <mat-radio-button [checked]="!emailReport" value="false">No
              </mat-radio-button>
              <mat-radio-button [checked]="emailReport" value="true">Yes
              </mat-radio-button>
          </mat-radio-group>
        </div>
        <div class="col-md-5">
          <label>Customers</label>
          <mat-select placeholder="--Select--" class="form-control" disableOptionCentering formControlName="name">
              <mat-option [value]="customer.firstName+' '+customer.lastName" id="customer.id" *ngFor="let customer of customers.clientManager">
                  {{customer.firstName +' '+customer.lastName}}
              </mat-option>
              <mat-option [value]="customer.email" id="customer.id" *ngFor="let customer of customers.supervisor">
                  {{customer.firstName +' '+customer.lastName}}
              </mat-option>
          </mat-select>
      </div>
        <div class="ml-md-auto col-md-3">
          <label>Type</label>
          <mat-select placeholder="--Select--" class="form-control" disableOptionCentering formControlName="type">
            <mat-option value='DAILY'> DAILY </mat-option>
            <mat-option value='WEEKLY'> WEEKLY</mat-option>
            <mat-option value='MONTHLY'> MONTHLY </mat-option>
        </mat-select>
        </div>
      </form>

A TypeScript file that is receiving a customer object

I have to dynamically change the email field according to the change in select bar value

@Input() customers;
// customers=[{firstName:'rishabh',lastName:'tripathi',email:'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6d191f041e050c0c0d052d0a000c0401430e0200">[email protected]</a>',type:"Daily"}]

ngOnInit() {
        this.form = this.fb.group({
          emailReport: [false, Validators.required],
          name : ['', Validators.required],
          email: [''],
          type: ['', Validators.required]
       },{updateOn: 'change'});

      this.form.valueChanges.subscribe(value =>{
       console.log(value)

    });

Answer №1

manageSubscription: Subscription
constructor() {
this.form = this.fb.group({
          emailOptIn:[false,[Validators.required]],
          fullName : ['',[Validators.required]],
          emailAddress:['',[]],
          subscriptionType: ['',[Validators.required]]
 });
}

ngOnInit() {
this.manageSubscription = this.form('fullName').valueChanges.subscribe(() => {
  if (this.users[0].hasOwnProperty('email'))
   this.form('emailAddress').setValue('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5f353730313b303a1f38323e3633713c3032">[email protected]</a>');
  }
})

ngOnDestroy() {
 this.manageSubscription.unsubscribe()
}
 

Answer №2

<div class="col-md-5">
      <label>Clients</label>
      <mat-select placeholder="--Choose--" class="form-control" disableOptionCentering formControlName="name" (selectionChange)="onSelectionChangeEvent($event)">
          <mat-option [value]="client" id="client.id" *ngFor="let client of clients.clientManager">
              {{client.firstName +' '+client.lastName }}
          </mat-option>
      </mat-select>
  </div>

You can monitor the event selectionChange on mat-select. Set the email value to the email form control.

onSelectionChangeEvent(client) {
  this.form.get('email').setValue(client.email);
}

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 you provide any tips on how to effectively incorporate slide-down and slide-up animations in Angular 4.*?

Hello, I'm new to working with Angular 4 and I'd like to create a slide down and up animation in Angular 4. Could someone please provide me with the necessary code? @Component({ ... animations: [] ... }) Thank you for your help! ...

Determine whether there is only one array in the object that contains values

At the moment, I am attempting to examine an array in order to determine if only one of its elements contains data. Consider this sample array: playersByGender = { mens: [], womens: [], other: [] }; Any combination of these elements may contain dat ...

script not found: typings-install

When running the command npm run typings-install, I encountered the following error: npm ERR! Windows_NT 6.1.7601 npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\n ...

I want to display a background color using this ng-template

enter image description hereMy code includes an ng-template that uses ngFor to generate internal HTML tags without the ability to add CSS properties. <ng-template *ngFor="let c of colors" contextMenuItem let-item (execute)="change_task_color($event.ite ...

Presenting information using mat-table in Angular 2

Everything seems to be working fine with the code as I am able to display the data in mat-cards successfully. However, when I try to display it in mat-tables, I encounter index errors. I have made sure to import matTableDataSource, DataSource, CdkTableModu ...

Can anyone provide a webpack configuration to package a webpack plugin together?

I'm in the process of developing a webpack plugin using typescript. Before I can publish it on NPM, I need to bundle the plugin code. However, I've encountered an exception stating that my plugin class is not a constructor. Below is the director ...

In Angular, I am working on manipulating classes by utilizing the $event parameter within the (click) event

Snippet of HTML code with button functionality <div fxLayout="column"gt; <h4>Click the button to select a service.</h4> <ng-container *ngFor="let service of services;"> <button class="service-button&q ...

Dependency on Angular's HTTP service inside a component

I've been experimenting with loading data from a static JSON file as part of my journey to learn angular templating. After some searching online, I came across a few examples. However, I want to steer clear of implementing a service until I have a be ...

How can I incorporate a background image into an Angular template without using a CSS file?

Can you please provide guidance on setting a background image in Angular using the ngFor directive within a carousel grid layout? <div class="slide slick-bg s-bg-1" *ngFor="let movie of nowPlaying" style="https://image.tmdb.org/ ...

Trouble accessing files in the assets folder of Angular 2

I am encountering a 404 error when attempting to access a local file within my application. I am unable to display a PDF that is located in a sub-folder (pdf) within the assets folder. I am using CLI. <embed width="100%" height="100%" src="./assets/pdf ...

What methods can I use to create an RXJS stream that only updates the state once all sequential calls have been successful?

Currently, I am delving into rxjs within the realm of Angular. However, I am facing difficulties in merging these concepts to accurately portray the following scenario: I initiate an HTTP request to an endpoint, which returns some data This data is then u ...

Position Bootstrap Modal in the center horizontally

I am working on an Angular project and struggling to center my Bootstrap 3 Modal horizontally on the screen. Despite trying various solutions like using text-align: center and align = "center", I have been unsuccessful. Can someone guide me on how to prope ...

Need an email verification request through firebase

Need help with sending email verification upon user sign up. Here is the code in provider/user.ts: onCreate(form: NgForm) { var user = new User(); user.name = form.value.name; user.email = form.value.email; user.contact = form.value.contact; if(form.valu ...

Assigning a Value to a Dropdown Menu in Angular

I have some JSON data that contains a True/False value. Depending on whether it is true or false, I want a specific option in a Select Dropdown to be automatically selected. This is the HTML code using Angular 16: <select name="reportNo" id=& ...

Documentation in TypeScript with JSDoc and using the new Rest type syntax

Encountering an issue while integrating TypeScript into a large existing React/Redux application. To test things out, I decided to convert one of my React files to a .ts file. My approach involves using JSDoc to add types to the imported JS files in order ...

Chrome reports "404 Not Found error: Cannot GET /" while using Angular 4 with Observable functions

I recently implemented observable data in my service, and it significantly improved the functionality of the application. https://i.sstatic.net/9h0KH.jpg This is an overview of my Service: import { Injectable } from '@angular/core'; import { H ...

Missing 'id' property in object {`id`} when utilizing GraphQL with Typescript

As a newcomer to coding and Typescript, I apologize for my limited knowledge. I am currently facing an issue where my application is unable to communicate with my API due to an error caused by the primary id key having a "?" symbol, like so: export interfa ...

Verify if a particular string is present within an array

I am in possession of the key StudentMembers[1].active, and now I must verify if this particular key exists within the following array const array= ["StudentMembers.Active", "StudentMembers.InActive"] What is the method to eliminate the index [1] from Stu ...

Issues encountered with <mat-error> functionality within a reactive form in an Angular 8 project

Utilizing a reactive approach, I am constructing a form using Angular and Material. Strangely, one of the errors generated by a custom validator is not being displayed, even though all other errors are functioning correctly. Below you can find the code sni ...

Using multiple where conditions in TypeORM

SELECT * FROM clients WHERE preferred_site = 'techonthenet.com' AND client_id > 6000; Is there a way to execute this in the typeorm query builder? ...