Retrieve input from text field and showcase in angular 6 with material design components

Take a look at the output image . In the code below, I am displaying the contents of the messages array. How can I achieve the same functionality with a text box and button in an Angular environment?

<mat-card class="example-card">
    <mat-card-header>
        <img mat-card-avatar src="https://cdn2.iconfinder.com/data/icons/chatbot-line/100/chatbot-07-512.png">
        <mat-card-title>Chat-Bot</mat-card-title>
        <mat-card-subtitle>IMB</mat-card-subtitle>
    </mat-card-header>
   <mat-divider></mat-divider>

<div *ngFor="let i of messages">
  {{i}}
</div>
      
<mat-form-field class="Message">
  <input matInput placeholder="Enter your Message">
</mat-form-field>
<button mat-fab>
  <mat-icon suffix>send</mat-icon>
</button>
</mat-card>
TypeScript

import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'projectCB';
messages=['Hi Bhanu','Hi War'];
}    

Answer №1

Connect your input field using the ngModel directive:

<input [(ngModel)]='userInput' matInput placeholder="Enter your Message">

Link your send-button with the click directive:

<button mat-fab (click)='send()'>
  <mat-icon suffix>send</mat-icon>
</button>

In your component file, include userInput variable and a send method:

userInput: string;

send(): void {
  this.messages.push(this.userInput);
  this.userInput = null;
} 

This is a basic way to implement your task. In a real application, it's recommended to create a service to manage data. Additionally, validate user input to prevent empty strings in your messages array.

For more information, refer to the Angular documentation for better understanding here

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

Styling with ngStyle and changing the background image

Having an issue with a component that has an @Input string value linking to an image. In my HTML file, I originally had: <div class="parallax" [ngStyle]="{'background-image': 'url({{parallaxImage}})'}"></div> This was not ...

Suggested imports in a yarn monorepo are not being automatically added when selected

I've noticed that many people are asking similar questions, but my situation seems a bit unique as I haven't found anyone else with the same issue. Currently, I'm working on a file in packages/frontend/client, specifically packages/frontend ...

What is the reason behind the input value becoming empty after a reset?

Currently, I am working with an input element reference: @ViewChild("inputSearch", { static: false }) This is how the template looks like: <input tabindex="0" type="text" (keydown)="keydownInputSearch($event)" #inputSearch autocomplete="off" ...

What event type should be used for handling checkbox input events in Angular?

What is the appropriate type for the event parameter? I've tried using InputEvent and HTMLInputElement, but neither seems to be working. changed(event) { //<---- event?? console.log({ checked: event.target.checked }); } Here's the com ...

Activate the field once the input for the other field is completed

I have a form where the last name field is initially disabled. How can I make it so that the last name field becomes enabled only when the first name is inputted? <form> <label for="fname">First name:</label><br> ...

Angular enables the use of multiple instances of a service from the parent component to the child component

I recently came across this discussion: Utilizing multiple instances of the same service. Can one utilize multiple instances of a service from parent to children? For instance, imagine having an ElementService in the ParentComponent with 2 separate instan ...

What is the best way to customize the styles of a reusable component in Angular2?

I am working with a reusable component called "two-column-layout-wrapper" that has its styles defined in the main .css file. In another module, I need to use this component but customize the width of two classes. How can I override these styles? import ...

In order to resolve the issue in nextjs 13 where the argument is of type 'any[] | null' and cannot be assigned to the parameter of type 'SetStateAction<never[]>', a potential solution may involve explicitly checking for null values

My current project uses Next.js 13 and is based on the Supabase database. I am attempting to fetch data from Supabase and assign it to a variable using useState, but encountering the following error: Argument of type 'any[] | null' is not assigna ...

Implement ExpressTS on vercel platform

I have recently developed an Express TypeScript project on GitHub and now I am attempting to deploy it to Vercel. The folder structure of the project is as follows, with 'dist' containing app.js and 'src' containing app.ts. dist dto mi ...

Expanding Arrays in TypeScript for a particular type

There is a method to extend arrays for any type: declare global { interface Array<T> { remove(elem: T): Array<T>; } } if (!Array.prototype.remove) { Array.prototype.remove = function<T>(this: T[], elem: T): T[] { return thi ...

What is the process of destructuring an array containing objects?

Examining this JSON structure: { "Person": { "UID": 78, "Name": "Brampage", "Surname": "Foo" }, "Notes": [ { "UID": 78, "DateTime": "2017-03-15T15:43:04.4072317", "Person": { ...

What does the term "progressive framework" refer to?

Recently, I've delved into the world of frontend frameworks such as Vue.js and AngularJS. In my research, I keep stumbling upon the term "Progressive Framework," but its true meaning still eludes me. Vue.js claims it can easily integrate with simple H ...

Using Angular Material's [mat-form-field], you can easily input a value into a text box

How can I programmatically add a value to a text box within a [mat-form-field] using a function? addValueToTextBox(){ ... } ...

Increase the current version number by adding the release candidate label and making it a prerelease using npm version command

Our team is in the process of streamlining our versioning and build processes for our Angular 2 applications through automation. We are interested in leveraging npm version However, we have encountered difficulty when attempting to add an 'rc' ...

Using Rust WebAssembly in Next.js

Seeking assistance with integrating a rust-generated wasm module into my NextJS project. This is how I am attempting to import the wasm: import init, { tokenize } from "@/wasm/lazyjson"; const Test = dynamic({ loader: async () => { ...

The API request does not provide randomized results and does not show any display

I am facing an issue with a button that is supposed to fetch a random user from an API. When I retrieve all the users, the information is displayed correctly. However, when I try to select a user at random, it does not work as expected. Also, it seems to a ...

Maximizing the potential of mouse positioning in Angular

I am working with an Angular form that has a textarea <textarea class="form-control" id="message" formControlName="message" (fo ...

Decorators do not allow function calls, yet the call to 'CountdownTimerModule' was executed

While building production files, the aot process is failing with this error message: Function calls are not supported in decorators but 'CountdownTimerModule' was called. I run the build command using npm run build -- --prod --aot and encounter ...

Transforming an Angular 1.x directive into Angular 2

I have been working on converting a wrap-bootstrap template with various widgets to Angular 2. The task of converting one particular widget has left me puzzled: .directive('changeLayout', function(){ return { restrict: 'A' ...

Ionic4: Troubleshooting the playback of audio files on a web-based application

Currently, my project involves using Ionic 4 in combination with Angular. I am facing a challenge where I need to play an audio file (mp3/wav) when an image is clicked. Despite working on this for a week, I have been unable to figure it out. Can anyone pr ...