wuno
wuno

Reputation: 9875

Adding Default Value To Text Input Angular 2

Background

I have a form with an input field containing the user's email address. I am using interpolation to add the email to the placeholder field.

Problem

I do not want the user to be able to change the email address in this field. I only want them to be able to see it. But I do want it to post with the form.

Question

I keep trying different ways and no matter what the form does not post the email. How can I bind it so that it will actually post the email address when the form is submitted?

Examples

I tried with readonly. That way they would not be able to change it.

 <input type="text" class="form-control" id="email" [(ngModel)]="personal.email" name="email" #email="ngModel" placeholder="{{auth.user.email}}" value="{{auth.user.email}}" readonly>

I tried without readonly just to see if it would work if I do not add any restriction flags.

 <input type="text" class="form-control" id="email" [(ngModel)]="personal.email" name="email" #email="ngModel" placeholder="{{auth.user.email}}" value="{{auth.user.email}}">

I know the email is accessible because I am adding it to the placeholder field and it shows up in the form. It just wont post.

Upvotes: 4

Views: 19882

Answers (2)

Asha Joshi
Asha Joshi

Reputation: 87

Here model is personal.email and the default value is auth.user.email

<input type="text" class="form-control" id="email" [(ngModel)]="personal.email = auth.user.email" name="email" #email="ngModel">

Upvotes: -1

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657308

The default value will be the value assigned to personal.email.

Alternatively you can bind to a different property

[(ngModel)]="personalEmail"

and assign a default value to personalEmail and on submit update persona.email in code or use

[ngModel]="personalEmail" (ngModelChange)="personal.email = $event"

to get the initial value from personalEmail and update personal.email when changes happen

This might also work (not tried)

[ngModel]="personal.email || 'defaultValue'" (ngModelChange)="personal.email = $event"

to only get 'defaultValue' assigned if personal.email is null

Upvotes: 11

Related Questions