'Get the value from the mat-input in angular material
As im new to the angular. I just want to get the value from the mat-input I need to get the value from the angular mat-input. Can someone help me to do this. Thanks in advance
<div fxLayoutAlign= "center center" fxFlexFill class="main-div">
<mat-card fxFlex= "20">
<mat-toolbar color="primary" c>Bonbloc Login</mat-toolbar>
<form fxLayoutAlign="stretch" fxLayout = "column" class="login-form">
<mat-form-field>
<input matInput required [(ngModel)] = "email" placeholder="email Id">
<mat-hint align="end">Min 5 characters</mat-hint>
</mat-form-field>
<mat-form-field>
<input matInput required [(ngModel)] = "password" type="password" placeholder="password">
</mat-form-field>
<button mat-raised-button type="submit" (click) = "login()">Login</button>
<h1>Hi {{email}} {{password}}</h1>
</form>
</mat-card>
login() {
console.log(this.email, this.password)
};
Solution 1:[1]
What part of it isn't working exactly? It looks as though it should be fine.
<input matInput required [(ngModel)]="email" placeholder="email Id">
Presumably you have a matching line in the .ts
declaring an email
field to bind to:
public email: string;
Or similar.
[(ngModel)]
Is a two-way binding, meaning whatever you set email
to programmatically will be put into the text box, and whatever the user puts into the text box will set email
's value.
Your login()
method should be able to see this...
public login(): void {
console.log('Entered email:', this.email);
}
Edit: Example StackBlitz showing the basic binding working. Not using matInput
, but that won't change the functionality.
Solution 2:[2]
html
<input matInput required [(ngModel)]="email" [value]="email" placeholder="your email" (change)="valuechange($event)">
component.ts
private email : string = '';
valuechange() {
console.log(this.email);
}
ng-model directive binds the value of HTML controls like input, select, text-area to a variable created in ts file. so it can be acted as two way binding
Solution 3:[3]
Use the name also Something like
<mat-form-field appearance="fill">
<form>
<mat-label>Insert Anything</mat-label>
<input type="text" matInput [(ngModel)] ="oName" name="oName" >
<mat-hint>Serie</mat-hint>
</form>
</mat-form-field>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | |
Solution 3 | octavio verdugo |