JITHU SEBASTIAN
JITHU SEBASTIAN

Reputation: 3

Get Value from a Input field Angular With Code

I want to take values from input to a function to alert here is my html

<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>

and here is my componet.ts

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 want to get value from input field and I want get value into components function

Upvotes: 0

Views: 927

Answers (2)

Chady BAGHDADI
Chady BAGHDADI

Reputation: 303

@ViewChild('titleInput') titleInput: 
ElementRef;

ngAfterViewInit() {
  // Put your logic here ...
}

i put the code here : https://stackblitz.com/edit/angular-ivy-b4hcqw?file=src%2Fapp%2Fapp.component.ts,src%2Fapp%2Fapp.component.html

Upvotes: 0

user20291198
user20291198

Reputation:

Create Variable to store input value:
component.ts

...
export class AppComponent {
input: string;
...

Add FormsModule to your module.ts if not already imported
module.ts

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

setup ngModel on your HTML:
html:

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

Important: Dont forget to add a Route to the component in your app-routing.module.ts

ngModel Docs

Upvotes: 1

Related Questions