There are many ways to get the value of a input
so much with Javascript as pure as with Angular using Typescript
, how is using the second most desirable option is to use the techniques provided by Angular, as the 2 ways below:
Based on this HTML, the first way is using the technique of two-way data Binding, along with a ngModel
:
<div class="form-group">
<label for="cpf"></label>
<input type="number" class="form-control" placeholder="Cpf" id="cpf" name="cpf" [(ngModel)]="cpf" />
</div>
<div class="form-group">
<input type="submit" class="btnSubmit" value="Cadastrar" />
</div>
In the class of its TS component:
export class SeuComponent {
public cpf: number; // propriedade que liga o html ao ts e vice-versa
cadastrar() {
console.log(this.cpf) // valor inserido no input
}
}
To learn more about two-way data Binding with Angular read here.
Another way would be to use the technique of variable template using a #
as a notation for a view variable along with @Viewchild() which is responsible for transporting the variable from Hmtl to Ts. If you use variable typing as type ElementRef
you can have everything you need for that HTML element including its value:
<div class="form-group">
<label for="cpf"></label>
<input type="number" class="form-control" placeholder="Cpf" id="cpf" name="cpf" #cpf />
</div>
<div class="form-group">
<input type="submit" class="btnSubmit" value="Cadastrar" />
</div>
In the class of its TS component:
export class SeuComponent {
@ViewChild("cpf") cpf: ElementRef; // propriedade que liga o html ao ts
cadastrar() {
console.log(this.cpf) // valor inserido no input
}
}
Obs: Depending on the version of Angular you are using you will need to do so @ViewChild("cpf", {static: true}) cpf: ElementRef;
Obs: You need to import the Angular form module on app module. to use the ngModel
on the component forms
Obs: Despite not having inserted in your question, you need a method in Ts to perform the data processing in the action of clicking the button as the registration that inserted in the examples
Obs: You can see an example with the two different ways implemented here.
see this: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
– Ricardo Pontual