Home > Net >  Get Value from a Input field Angular With Code
Get Value from a Input field Angular With Code

Time:12-09

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

<div >
  <input #titleInput *ngIf="isClicked"  type="text"  ><br>
  <button (click)="OnClick()" >
    Show 
  </button>
  <button (click)="Send(titleInput.value)" >
    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

CodePudding user response:

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

CodePudding user response:

@ViewChild('titleInput') titleInput: 
ElementRef;

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

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

  • Related