有条件地将输入字段在Angular

有条件地将输入字段在Angular

本文介绍了有条件地将输入字段在Angular 2或4中设为只读:建议+最佳/采用哪种方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图回答其他人的问题.在意识到这一点后,我对某些事情充满了不确定性.我希望有人可以就编号为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.

  1. 在Angular 2+中直接用@ViewChild引用HTMLInputElementElement是不好的做法吗?只是,我经常看到使用ElementRef或从ElementRef链接到nativeElement的示例.
  1. Is referencing HTMLInputElement or Element directly with @ViewChild in Angular 2+ a bad practice?Only, I've often seen examples using ElementRef or chaining off to nativeElement from ElementRef.

由于VS Studio没有针对这些的Intelli-sense,我突然觉得自己在黑暗中进行编码.也就是说,您永远不会收到有关方法setAttribute或removeAttribute,其参数要求等的反馈.(我也知道也要投射)

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)

  1. 然后,查看文档后,我怀疑您可以直接在HTML模板中的输入上执行此操作:


<input [attr.readonly]= "isReadOnly">

IIRC,我认为您必须对Typescript中的属性进行此操作:

IIRC I think you have to do this way with a property get in Typescript:

get isReadOnly() :boolean {
}

这样有效吗?

  1. 我想知道,您也可以在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.

推荐答案

您需要使用以下内容(角度4):

You need to use the following (Angular 4):

<input [readonly]="isReadOnly">

如果使用att.readonly,则输入将始终是只读的,因为即使readonly属性的值为false,该属性也会存在.通过使用[readonly],只有isReadOnly为true时,Angular才会放置属性.

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中设为只读:建议+最佳/采用哪种方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 15:51