Conditional readonly on ion-input

I’ve got a bit of a newbie question here I think. I want to programatically set the readonly property of an ion-input.

From what I’ve read, I should do this in the following way:

<ion-input type="number" [readonly]="isReadonly"></ion-input>

and in my JS file I should have a function that returns true or false to toggle the readonly tag:

isReadonly() {return true;}

This doesn’t seem to be working for me, as the input is writable no matter the value returned form the readonly function - inspecting the HTML reveals that the readonly property is never added to the input tag. Adding a console.log in the isReadonly function is also not written to the console, so I believe its not even being called, but I don’t know why!

Any pointers on how to get this to work would be greatly appreciated!

Could you try changing it to this?

[readonly]="isReadonly()"

Note the () I think you need it because you are trying to use a function instead of a variable.

2 Likes

I should have mentioned that I had also tried with the parentheses, but I still get the same result.

I’ve also tried setting a variable (this.isReadonly = true in the constructer) and this also doesn’t seem to work.

Any other thoughts on how I could get this to work?

Can you do a ionic info so we know what you are working with? I am a typescript guy though :stuck_out_tongue:

Your system information:

Cordova CLI: 6.1.1
Gulp version: CLI version 3.9.1
Gulp local: Local version 3.9.1
Ionic Framework Version: 2.0.0-beta.4
Ionic CLI Version: 2.0.0-beta.25
Ionic App Lib Version: 2.0.0-beta.15
ios-deploy version: 1.8.6
ios-sim version: 5.0.8
OS: Mac OS X Yosemite
Node Version: v4.4.2
Xcode version: Xcode 7.0 Build version 7A220

This seems to be a bug with ion-input.

Could you open an issue on github about this.

Woohoo, its not just me - opening an issue on Github now :slight_smile:

1 Like

Thanks for opening the issue, I’ll just link it here in case anyone else finds this topic:

readonly="{{isReadonly}}"
2 Likes

The advice in the previous post is bad. Always prefer [foo]="bar" over foo="{{bar}}" because otherwise you will get unpleasantly surprised when binding non-strings.

7 Likes

Thanks. This has helped me in my code

On the link from iignatov, the subject is closed because you can use the attribute ‘disabled’ instead of ‘readonly’ and it works.

instead of [readonly] use [attr.readonly] this solved it for me

  <div *ngIf="!isReadonly">
    <ion-textarea
      [(ngModel)]="feedback"
      class="name"
      maxlength="128"
      clearOnEdit="true"
    ></ion-textarea>
  </div>
  <div *ngIf="isReadonly">
    <ion-textarea
      readonly
      [(ngModel)]="feedback"
      class="name"
      maxlength="128"
      clearOnEdit="true"
    ></ion-textarea>
  </div>

That looks like a lot of needless duplication to me. Did binding attr.readonly as @swforlive suggested not behave as you expected?