Alex
Alex

Reputation: 81

Angular: text input won't set to a default value

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

Answers (5)

Dominik Br&#225;zdil
Dominik Br&#225;zdil

Reputation: 493

You can use

[defaultValue]="myDefaultValue"

without Angular changing the variable 'myDefaultValue' on the input change.

Upvotes: 1

sabrine abdelkebir
sabrine abdelkebir

Reputation: 83

you can add this.userName = 'Bob'; in the file .ts , remove init and value='Bob' from html.

Upvotes: 0

Lia
Lia

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

harkesh kumar
harkesh kumar

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

sah1
sah1

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

Related Questions