有条件地在 Angular 2 或 4 中将输入字段设为只读:建议 + 最佳/采用哪种方法 [英] Conditionally make input field readonly in Angular 2 or 4: Advice + Best/which way to do it
问题描述
我试图回答别人的问题.在这样做的过程中,我意识到我对一些事情存在相当多的不确定性.我希望有人可以提供有关编号 1..4 的反馈:
I was attempting to answer someone elses question. And in doing so realised there was quite a bit of uncertainty in my mind about a few things. I'm hoping someone can provide feedback on the numbered points 1..4:
HTML 的相关部分:
Relevant section of HTML:
<input type="text" placeholder="Club Name" #clubName>
将此添加到 Typescript 组件.
Add this to Typescript component.
// class properties
@ViewChild('clubName')
inp:HTMLInputElement; // Could also use interface Element
// conditionally set in some other methods of class
inp.setAttribute('readonly', 'readonly');
inp.removeAttribute('readonly');
不得不说这对我来说是一个灰色地带.
Have to say this is a grey area for me.
- 在 Angular 2+ 中直接使用
@ViewChild
引用HTMLInputElement
或Element
是不好的做法吗?只是,我经常看到使用ElementRef
或从ElementRef
链接到nativeElement
的示例.
- Is referencing
HTMLInputElement
orElement
directly with@ViewChild
in Angular 2+ a bad practice? Only, I've often seen examples usingElementRef
or chaining off tonativeElement
fromElementRef
.
由于 VS Studio 没有这些智能感知,我突然觉得我在黑暗中编码.即,您永远不会得到有关 setAttribute 或 removeAttribute 方法、它们的参数要求等的反馈.(我也知道 As 可以投射)
Since VS Studio doesn't have Intelli-sense for those, I suddenly feel like I'm coding in the dark. i.e, you never get feedback about methods setAttribute or removeAttribute, their parameter requirements etc. (I'm aware of As to cast too)
- 然后,在查看文档后,我怀疑您可以直接在 HTML 模板中的输入上执行此操作:
<小时>
<input [attr.readonly]= "isReadOnly">
IIRC 我认为您必须使用 Typescript 中的属性 get 这样做:
IIRC I think you have to do this way with a property get in Typescript:
get isReadOnly() :boolean {
}
这种方式有效吗?
- 我想知道,您是否也可以在 HTML 模板中执行方法语法:
<小时>
<input [attr.readonly]= "isReadOnly()">
打字稿
isReadOnly() :boolean {
}
这种方式有效吗?
更新:还有 *ngIF,因此您可以输出具有相同名称的两个输入元素之一.但对我来说,这听起来像是敲碎坚果的大锤.
Update: There is also *ngIF so you output one of two input elements with same name. But that sounds to me like a sledgehammer to crack a nut.
推荐答案
你需要使用以下(Angular 4):
You need to use the following (Angular 4):
<input [readonly]="isReadOnly">
如果您使用 att.readonly
,那么输入将始终是只读的,因为即使 readonly
属性的值为 false,它也会存在.通过使用 [readonly]
Angular 只会在 isReadOnly
为真时放置属性.
If you use att.readonly
then the input will always be read-only because the readonly
attribute will be present even if its value is false. By using [readonly]
Angular will only place the attribute if isReadOnly
is true.
在 HTML 中,以下内容足以使输入变为只读:
In HTML, the following is sufficient to cause an input to be read-only:
<input readonly>
这篇关于有条件地在 Angular 2 或 4 中将输入字段设为只读:建议 + 最佳/采用哪种方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!