Bhanu Prakash War
Bhanu Prakash War

Reputation: 168

Get data from textbox and display in angular 6 using materials

Check output image From the following code I display the contents of messages array, but how can I achieve the same with textbox button function in angular

<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 you 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'];
}    

Upvotes: 0

Views: 928

Answers (1)

Roman Lytvynov
Roman Lytvynov

Reputation: 503

Bind your input with ngModel directive:

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

Bind your send-button with click directive:

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

In your component file add userInput field and send method:

userInput: string;

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

This is the simplest implementation of your task. In real application you better to create service to manage data. Also you need to validate user input, for example, to avoid empty strings in your messages array.

Read the angular documentation for better understanding https://angular.io/tutorial/toh-pt1

Upvotes: 1

Related Questions