wuno wuno - 8 days ago 6
TypeScript Question

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.

Answer

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