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:
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.
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)
<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?
<input [attr.readonly]= "isReadOnly()">
Typescript
isReadOnly() :boolean { }
Is this way valid?
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.
The readonly attribute is a boolean attribute. When present, it specifies that an input field is read-only. A read-only input field cannot be modified (however, a user can tab to it, highlight it, and copy the text from it).
Task: Conditionally make input field readonly 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');
AngularJS ng-readonly DirectiveThe ng-readonly directive sets the readonly attribute of a form field (input or textarea). The form field will be readonly if the expression inside the ng-readonly attribute returns true. The ng-readonly directive is necessary to be able to shift the value between true and false .
A readonly element is just not editable, but gets sent when the according form submits. A disabled element isn't editable and isn't sent on submit.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With