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.
- 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
.
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)
- 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?
- 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.
2 & 3
on seperate occasions depending on what I need to compute to determine the bool.