typescript 将默认值添加到文本输入 Angular 2
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40882211/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding Default Value To Text Input Angular 2
提问by wuno
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.
我有一个包含用户电子邮件地址的输入字段的表单。我正在使用插值将电子邮件添加到placeholder
字段中。
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
?
我不断尝试不同的方式,也不管什么form
没有post
电子邮件。我怎样才能bind
让它post
在表单时实际使用电子邮件地址submitted
?
Examples
例子
I tried with readonly
. That way they would not be able to change it.
我试过readonly
。这样他们就无法改变它。
<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.
我试过不readonly
只是想看看如果我不添加任何限制标志它是否会起作用。
<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.
我知道电子邮件是可访问的,因为我将它添加到占位符字段并显示在表单中。它只是不会发布。
回答by Günter Z?chbauer
The default value will be the value assigned to personal.email
.
默认值将是分配给 的值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
并为代码中的personalEmail
提交更新persona.email
或使用分配一个默认值
[ngModel]="personalEmail" (ngModelChange)="personal.email = $event"
to get the initial value from personalEmail
and update personal.email
when changes happen
获取初始值personalEmail
并personal.email
在发生更改时更新
This might also work (not tried)
这也可能有效(未尝试)
[ngModel]="personal.email || 'defaultValue'" (ngModelChange)="personal.email = $event"
to only get 'defaultValue'
assigned if personal.email
is null
只得到'defaultValue'
分配,如果personal.email
是null
回答by Asha Joshi
Here model is personal.email
and the default value is auth.user.email
这里模型是personal.email
,默认值是auth.user.email
<input type="text" class="form-control" id="email" [(ngModel)]="personal.email = auth.user.email" name="email" #email="ngModel">