Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

Conditionally make input field readonly in Angular 2 or 4: Advice + Best/which way to do it

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:

Task: Conditionally make input field readonly

Relevant section of HTML:

<input type="text" placeholder="Club Name" #clubName>

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. 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.

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. Then, after looking at the docs, I suspect you can do this directly on your input in the HTML template:

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

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

get isReadOnly() :boolean {
}

Is this way valid?


  1. I'm wondering, can you do the method syntax too in the HTML template:

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

Typescript

isReadOnly() :boolean {
}

Is this way valid?


4. In summary, what's the best approach?

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.

question from:https://stackoverflow.com/questions/45226354/conditionally-make-input-field-readonly-in-angular-2-or-4-advice-best-which-w

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to use the following (Angular 4):

<input [readonly]="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.

In HTML, the following is sufficient to cause an input to be read-only:

<input readonly>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...