// in html
<input #nameInput type="text" class="form-control" placeholder=''/>
// in add-player.ts file
import { OnInit, ViewChild, ElementRef } from '@angular/core';
export class AddPlayerComponent implements OnInit {
@ViewChild('nameInput') nameInput: ElementRef;
constructor() { }
ngOnInit() { }
addPlayer() {
// you can access the input value via the following syntax.
console.log('player name: ', this.nameInput.nativeElement.value);
}
}
In Angular 11, if you have your template set up so that you have a form tag which contains the input tag and there also exists a button that you can click, the following code shows how to alert the input tag's value via two-way data binding:
Note that the name attribute in the template is required here, otherwise you'll get an error message in the developer console saying the following:
Error: If ngModel is used within a form tag, either the name attribute must be set or the form
control must be defined as 'standalone' in ngModelOptions.
Example 1: <input [(ngModel)]="person.firstName" name="first">
Example 2: <input [(ngModel)]="person.firstName" [ngModelOptions]="{standalone: true}">
This is the method I like to use. The reason I prefer this method is that you can reference the input value in functions other than the one you've directly attached to the form, and you can also add validators and pre-set values if you wish: