Reputation: 489
<form #apiForm="ngForm" (submit)="onSubmit(apiForm);">
<div class="apply-form">
<div>
<label>API Name <span class="astrik">*</span></label>
<input type="text" placeholder="e.g presonal key" name="name" />
</div>
<div>
</form>
I want to get the value of input so that I could validate it.
onSubmit(apiForm: any) {
console.log(apiForm.controls.name.value)
console.log(apiForm.name.value)
if(apiForm.name.value) {
alert()
}
}
Upvotes: 2
Views: 7910
Reputation: 100
component.html
<input type="text" class="form-control is-valid m-2" #userMail="ngModel" [(ngModel)]="service.UserDataObj.userMail"
name="userMail" id="userMail" placeholder="Enter EmailId">
component.ts
onsubmitSignin(form:NgForm)
{
console.log("Form values-\n
Mail: "+ form.form.get('userMail')?.getRawValue()+",
Pass: "+ form.form.get('userPassword')?.getRawValue());
}
here form is a 'NgForm' type object access value form 'form.form.get()' here my 'ngModelVal' is userMail from '#userMail="ngModel"'
and reminder to use 'getRawValue()' function to get your exact value
so syntax will be,
> form.form.get('<ngModelVal>')?.getRawValue())
Edited: sorry forgot to add one more option if above line doesn't work
> form.form.get('<ngModelVal>')?.value)
Hope you got help,have a great time. (P.S-I used Angular 16 in vscode(Win-64))
Upvotes: 1
Reputation: 146
// You can achieve this using ngModel. don't forget to import FormsModule in your app.module.ts file.
<input type="text" placeholder="e.g presonal key"
[(ngModel)]="apiForm.name"/>
apiForm={name:null};
onSubmit(apiForm: any) {
console.log(this.apiForm.name)
}
Upvotes: 0
Reputation: 2820
Here, you are using template driven forms,
We need to explicitly register each template control with the ngForm
directive. To do so we need to do two things to each template form control:
Add the ngModel
directive
Add the name attribute
<form #apiForm="ngForm" (submit)="onSubmit(apiForm);">
<div class="apply-form">
<div>
<label>API Name <span class="astrik">*</span></label>
<input type="text" placeholder="e.g presonal key" name="name" ngModel/>
</div>
<div>
</form>
you can get the json object of form by using apiForm.value
.
and instead of using validation in function, I will recommend you to use form control states and add validation message on template.
Refer Template Driven Forms in Angular
Let me know if you have any doubts.
Upvotes: 1
Reputation: 667
use [(ngModel)] for your input:-
<input type="text" placeholder="e.g presonal key" name="name"
[(ngModel)]="apiForm.name"/>
on Typescript file declare apiForm
apiForm = {
name:''
}
onSubmit(apiForm: any) {
console.log(apiForm.controls.name.value)
console.log(apiForm.name.value)
if(apiForm.name.value) {
alert()
}
}
Upvotes: 0