Obtaining Input Field Value in Angular Using Code

How can I pass input values to a function in order to trigger an alert? Check out the HTML code below:

<div class="container p-5 ">
  <input #titleInput *ngIf="isClicked" type="text" class="col-4"><br>
  <button (click)="OnClick()" class="btn btn-primary col-2 ">
    Show 
  </button>
  <button (click)="Send(titleInput.value)" class="btn btn-success col-2 m-3">
    Send
  </button>
</div>

Additionally, here is the corresponding component.ts file:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

Send(data: any) {
  alert(data);
}

OnClick() {
  this.isClicked = true;
}
  
title = 'demoproject1';
isClicked = false;
}

I need assistance retrieving the value entered into the input field and passing it to the function within my component.

Answer №1

Declare a variable to hold the input value:
within your component.ts file

...
export class MainComponent {
userInput: string;
...

If not already included, add FormsModule to your module.ts file
module.ts

import { FormsModule } from '@angular/forms';

Implement ngModel in your HTML template:
html:

<input type="text" [(ngModel)]="userInput" ></-input> 

Note: Remember to configure a Route for the component within your app-routing.module.ts

Learn more about ngModel here

Answer №2

@ViewChild('titleInput') titleInput: 
ElementRef;

ngAfterViewInit() {
  // Your unique logic goes here...
}

The code snippet can be found at: https://example.com/code-snippet

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

I am looking for an image search API that supports JSONP so that users can easily search for images on my website

I am currently in the process of creating a blog platform. My goal is to allow users to input keywords on my site and search for images directly within the website. This way, I can easily retrieve the URL of the desired image. ...

When a reaction function is triggered within a context, it will output four logs to the console and

My pokemon API application is encountering some issues. Firstly, when I attempt to fetch a pokemon, it continuously adds an infinite number of the same pokemon with just one request. Secondly, if I try to input something again, the application freezes enti ...

Implementing callback within another function: A guide

I'm embarking on the journey of creating a node waterfall using the async module. I've just dipped my toes into the waters of asynchronous programming in node. Essentially - how do I trigger callback() within the http.request function to proceed ...

Combine two arrays in MongoDB where neither element is null

Issue I am looking to generate two arrays of equal length without any null elements. Solution I have managed to create two arrays, but they contain some null values. When I remove the null values, the arrays are no longer of equal length. aggregate([ ...

Tips for utilizing a for loop within an array extracted from a jQuery element for automation

I am looking to streamline the process using a for loop for an array containing 10 image files in the parameters of initialPreview and initialPreviewConfig. My envisioned solution involves the following code snippet: for (i = 0; i < 11; i++) { "< ...

Encountering error code 128 while attempting to download npm packages

After attempting to install jspdf using the command npm install jspdf --save, I encountered the following error: npm ERR! code 128 npm ERR! Command failed: git submodule update -q --init --recursive npm ERR! error: waitpid for git-submodule failed: No chi ...

Retrieve various data types through a function's optional parameter using TypeScript

Creating a custom usePromise function I have a requirement to create my own usePromise implementation. // if with filterKey(e.g `K=list`), fileNodes's type should be `FileNode` (i.e. T[K]) const [fileNodes, isOk] = usePromise( () => { ...

Having trouble with JavaScript/JQuery not functioning properly in HTML content loaded using the load() method

My goal is to load an input form from a separate file called new_machine.php into my index.php. This form includes an input with a dropdown that retrieves options from a MySQL database and displays them as anchors. The issue arises when I attempt to manipu ...

How can we leverage the nullish coalescing operator (`??`) when destructuring object properties?

When working with ReactJS, I often find myself using a common pattern of destructuring props: export default function Example({ ExampleProps }) { const { content, title, date, featuredImage, author, tags, } = ExampleProps || {}; ...

What steps can be taken to resolve the Angular error stating that the property 'bankCode' is not found on type 'User' while attempting to bind it to ng model?

I'm encountering an issue with my application involving fetching values from MongoDB and displaying them in an Angular table. I've created a user class with properties like name and password, but I keep getting errors saying that the property doe ...

Tips for passing a variable from one function to another file in Node.js

Struggling to transfer a value from a function in test1.js to a variable in test2.js. Both files, test.js and test2.js, are involved but the communication seems to be failing. ...

The output from Angular Validator.pattern() may differ from that generated by online regex engines

Currently, I am facing an issue with my form group and a regular expression used to validate names. The criteria for the name input field are: It must be required. It should be alphanumeric. It must start with alphabets. It cannot contain any special char ...

Tips for dynamically populating JSON data using a dropdown selection?

I am currently exploring HTML forms as a new web developer. I have been experimenting with displaying JSON data in a div based on a selection from a dropdown menu using jQuery in Chrome. However, my code does not seem to be functioning properly. Even tho ...

Tips for designing a multi-level dropdown navbar

I am currently facing an issue with designing a navbar. I am aiming for Multi-Level Dropdowns, but whenever I click on More Services, it automatically closes the main dropdown menu. I have experimented with various approaches, but none of them seem to be ...

Running JavaScript function from AJAX response containing both HTML and JavaScript code

For my first time using AJAX to prevent page refresh upon form submission, everything works flawlessly. The data is received in HTML form and placed into the designated div. However, I am encountering an issue with one of the JavaScript functions responsib ...

Certain mobile devices experiencing issues with AngularJS filters

Currently, I am attempting to filter an AngularJS array by utilizing custom filters within a controller. The filters are functioning correctly on certain mobile devices, yet they are not working on others. Here is the code snippet that I am using: var a ...

Display the new data from an array that has been created following a subscription to Angular Firestore

I am struggling to access the content of a variable that holds an array from a Firebase subscription. The issue I am facing is that I am unable to retrieve or access the value I created within the subscription. It seems like I can only use the created valu ...

The ngOnChanges lifecycle hook is triggered only once upon initial rendering

While working with @Input() data coming from the parent component, I am utilizing ngOnChanges to detect any changes. However, it seems that the method only triggers once. Even though the current value is updated, the previous value remains undefined. Below ...

Quick inquiry about referencing state variables in the render method in React Native

Initially, I assumed it was just a simple syntax error, but now I'm beginning to think that it might be related to a bigger concept concerning hierarchy and inheritance. I am currently working on an app in react native (expo) where I aim to display a ...

Having trouble navigating through multiple layers of nested array data in react js

I need help understanding how to efficiently map multiple nested arrays of data in a React component and then display them in a table. The table should present the following details from each collection: title, location, description, and keywords. Below ...