set a value to a concealed ngModel

Is there a way to automatically assign the same value to two input fields in Angular? In this case, the variable first needs to be set to second without requiring user input.

Model

export class Exp{

    id: number;
    first: any;
    second: any;

}

HTML

<label>Enter value for first:</label>
<input type="text" [(ngModel)]="exp.first" class="form-control">

<input type="hidden" [(ngModel)]="exp.second" class="form-control">

<button (click)="add()">Add</button>

TypeScript

add(){
this.myService.add(this.exp).subscribe(
   data => {this.exp=data;}, 
   error => {console.log('error');}
 );

}

Answer №1

Check out this Stackblitz demonstration.

To start off, you can assign a template reference variable to the initial input which has the ngModel directive:

<input type="text" #first="ngModel" [(ngModel)]="exp.first" class="form-control">

Then, in your TypeScript code, you can access this control, monitor its changes, and update the value of second in the model accordingly:

@ViewChild('first') _ngModelFirst: NgModel;

// It is recommended to unsubscribe from all observables
// when this component is being destroyed
private _destroy$ = new Subject<void>();

exp: Exp = {
  id: 1,
  first: '',
  second: ''
};

ngAfterViewInit() {
  this._ngModelFirst.valueChanges
    // To ensure proper cleanup, use takeUntil(this._destroy$)
    .pipe(takeUntil(this._destroy$))
    .subscribe((value: string | null) => {
      this.exp.second = value;
    });
}

ngOnDestroy() {
  if (this._destroy$ && !this._destroy$.closed) {
    this._destroy$.next();
    this._destroy$.complete();
  }
}

https://i.sstatic.net/WtGiy.gif

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

Angular now displays an unsupported Internet Explorer version message instead of showing a white screen

I am responsible for developing new features and maintaining an Angular application (version 8.3.4). Initially, we wanted the application to be compatible with all versions of Internet Explorer, but that turned out to be impractical. While the application ...

How to fetch and parse a JSON file in Angular using HTTP request

Looking to access a JSON file within my local project for some basic configuration. Here is the code snippet: myM: any; constructor(private http: Http) { this.http.get('config.json') .map((res: Response) => res.json()) ...

How can I ensure that several components are correctly subscribing to an observable at the same time?

I am working on a client service that has a method: receiveData (params) { return this.http.get(url, { params: params }); } Then there is a service that utilizes this: getData () { return this.client.receiveData(this.params); } Later on, there is a c ...

Is there a way to store session variables in Angular without the need to make an API call?

I am currently working with a backend in PHP Laravel 5.4, and I am looking for a way to access my session variables in my Angular/Ionic project similar to how I do it in my Blade files using $_SESSION['variable_name']. So far, I have not discove ...

Complication with AOT compilation in ap-angular2-fullcalendar causing errors

I'm encountering a problem while trying to do AOT for my Angular 4 application, specifically when referencing ap-angular2-fullcalendar. Below are the configurations in my rollup-config.js file: ** import rollup from 'rollup'; import ...

Destiny does not uncover personalized typing

I am currently setting up a test for a component that utilizes a third-party JavaScript library. Everything works smoothly in the project scenario, but when I attempt to run the standard stand in Karma, an error is triggered: typing_name is not defined ...

ngx-datatable - personalized columns featuring interactive buttons

I am currently working with a table using ngx-datatable where I have created an "actions" column for CRUD operations and added buttons. However, I am facing an issue where the selected row and its column values are not being recognized within my function. ...

Combining meanings within a geometric interface

When setting up my routes, I like to include an additional field in the configuration. This is how I do it: app.config([ '$routeProvider', ($routeProvider: ng.route.IRouteProvider) => { $routeProvider ...

Angular's import and export functions are essential features that allow modules

Currently, I am working on a complex Angular project that consists of multiple components. One specific scenario involves an exported `const` object in a .ts file which is then imported into two separate components. export const topology = { "topolo ...

Exploring the nuances between Angular and Svelte in change detection mechanisms

In my daily work, I rely on Angular but also am taking the time to learn Svelte. As far as I know, neither Angular nor Svelte utilize a virtual dom and diffing process for change detection. Instead, they both have their own mechanisms for detecting chang ...

Angular application code modifications do not reflect in the browser

After making changes to the HTML file of an Angular component, the browser does not reflect those changes when connected to localhost. Even though the old string is no longer present in the project, the browser continues to display it. Interestingly, openi ...

Error message: Unable to retrieve parameter value from Angular2 ActivatedRoute

I am attempting to showcase the value of the activated route parameter on the screen, but I am facing difficulties. In the initial component, my code looks like this: <ul *ngFor="let cate of categories;"> <li (click)="onviewChecklists(cate.id) ...

In React Router v6, you can now include a custom parameter in createBrowserRouter

Hey there! I'm currently diving into react router v6 and struggling to add custom params in the route object. Unfortunately, I haven't been able to find any examples of how to do it. const AdminRoutes: FunctionComponent = () => { const ...

Unable to interact with the page while executing printing functionality in

component: <div class="container" id="customComponent1"> New Content </div> <div class="container" id="customComponent2"> different content </div> ...

"Learn the process of extracting information from a database and exporting it to a CSV file with Angular 2

Currently, I am facing an issue where I need to retrieve data from a database and export it to a CSV file. While I am able to fetch all the data successfully, I am encountering difficulty when trying to fetch data that is in object format as it shows up as ...

Querying data elements using Graphql mutations: a step-by-step guide

const MUTATION_QUERY = gql` mutation MUTATION_QUERY( $name: bigint! ) { insert_name( objects: { name: $name } ) { returning { id name } } } `; const [onClick, { error, data }] = useMut ...

What is the process for updating the background color of the header in ngx datatable?

I am looking to change the background color of the table header to blue. This is the HTML code I have: <ngx-datatable class="material" [rows]="rows" [columnMode]="'force'" [headerHeight]="50" [footerHe ...

The "ng2-CKEditor" package is experiencing compatibility issues with TypeScript in Angular 2

Currently, I am in the process of setting up CKEditor in my angular2 application. My backend platform is node.js and for this purpose, I am utilizing the ng2-CKEditor npm module. Below, you can find snippets from respective files. index.html:: <html& ...

Exploring the concept of inheritance and nested views within AngularJS

I've encountered a challenge while setting up nested views in AngularJS. Utilizing the ui-router library has been beneficial, but I'm facing issues with separate controllers for each view without proper inheritance between them. This results in h ...

Having trouble getting useFieldArray to work with Material UI Select component

I am currently working on implementing a dynamic Select field using Material UI and react-hook-form. While the useFieldArray works perfectly with TextField, I am facing issues when trying to use it with Select. What is not functioning properly: The defau ...