Reputation: 81
I have this 'Username' input:
<div class="form-group">
<label for="userName">Username</label>
<input name='userName' ngModel id="userName" type="text"
ng-model="userName" init="userName='Bob'" value="Bob" >
</div>
I want to set the input to 'Bob' by default but this doesn't work. If i delete 'ngModel' it works and I need it otherwise it won't sent my username to server.
This is in the begging of the form(the action that happens when I press submit button):
<form #physicians="ngForm" (ngSubmit)="onFormSubmit(physicians.value)">
And this the controller:
onFormSubmit(data) {
console.log(data);
this.adminService.updateUser(data).subscribe((responseData: any) => {
this.router.navigate(['/']);
},
(err: HttpErrorResponse) => {
this.isSignupError = true;
this.errorText = err.error['message'];
});
}
How can I fix this?Thank you!
Upvotes: 0
Views: 19459
Reputation: 493
You can use
[defaultValue]="myDefaultValue"
without Angular changing the variable 'myDefaultValue' on the input change.
Upvotes: 1
Reputation: 83
you can add this.userName = 'Bob'; in the file .ts , remove init and value='Bob' from html.
Upvotes: 0
Reputation: 11982
you should do something like:
ts code:
export class AppComponent {
userName;
constructor() {
this.userName = 'Bob';
}
}
html:
<form #form="ngForm" novalidate>
<label>userName:</label>
<input type="text" name="userName" [(ngModel)]="userName" required minlength="2" maxlength="10" #userNameDir="ngModel">
<pre>errors: {{userNameDir.errors | json}}</pre>
<button type="button" [disabled]="form.invalid" (click)="onFormSubmit(form.value)">submit</button>
<pre>form.value: {{form.value | json}}</pre>
<pre>form.errors: {{form.errors | json}}</pre>
<pre>form.status: {{form.status | json}}</pre>
<pre>form.dirty:{{form.dirty | json}}</pre>
</form>
DEMO.
Upvotes: 2
Reputation: 883
<form [formGroup]="physicians" (ngSubmit)="onSubmit(physicians.value)">
<div class="form-group">
<label for="userName">Username</label>
<input name='userName' type="text" formControlName="userName" >
</div>
TS FILE code
Put this in ngOnInit
this.physicians= this._formBuilder.group({
userName:['bob']
})
onFormSubmit(data) {
console.log(data);
this.adminService.updateUser(data).subscribe((responseData: any) => {
this.router.navigate(['/']);
},
(err: HttpErrorResponse) => {
this.isSignupError = true;
this.errorText = err.error['message'];
});
Upvotes: 0
Reputation: 400
Try using the following code: HTML:
<input name='userName' id="userName" type="text" [(ngModel)]="userName">
TS:
userName='Bob' // when you have declared the variable
Upvotes: 0