Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
111
rated 0 times [  112] [ 1]  / answers: 1 / hits: 21856  / 6 Years ago, thu, may 17, 2018, 12:00:00

I have a simple form


<form role="form" (submit)="login()">
<input type="text" name="username" id="username" required="required" [ngModel]="credentials.username"/>
<input type="password" name="password" id="password" required="required" [ngModel]="credentials.password" />
<button type="submit">Sign in</button>
</div>
</form>

and a component ts.


export class LoginComponent implements OnInit {
credentials = {username: '', password: ''};

constructor(private loginService: LoginService, private http: HttpClient, private router: Router) { }

ngOnInit() { }

login() {
console.log(this.credentials);
this.loginService.authenticate(this.credentials, () => {
this.router.navigateByUrl('/');
});
return false;
}
}

service


authenticate(credentials, callback) {
console.log(credentials);
const headers = new HttpHeaders(credentials ? {
authorization : 'Basic ' + btoa(credentials.username + ':' + credentials.password)
} : {});
}

My problem is that the credentials are always ''. Shouldn't the ngModel update these values automatically?


More From » angular

 Answers
46

You should use [(ngModel)] to set values like this -



<input type=text name=username id=username placeholder=Username required=required [(ngModel)]=credentials.username/>
<input type=password name=password id=password placeholder=Password required=required [(ngModel)]=credentials.password />


As of now, you are using [ngmodel] which is just attribute binding to set value into your DOM and display it back.



But if you want to update value from view part you should use two way data binding [(ngModel)]


[#54418] Saturday, May 12, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hailey

Total Points: 355
Total Questions: 91
Total Answers: 91

Location: India
Member since Wed, Aug 4, 2021
3 Years ago
;