arj
arj

Reputation: 983

Unable to make input text field as read only angular 6

My requirement is to make text field as read only based on a value. I have tried two ways, both have failed. The following is my code.

Using ngClass

HTML Code

<input type="text" [ngClass]="{inputDisabled : data ? true:false}" id="req_name" value={{data.name}}
            name="req_name"> 

Css Code

.inputDisabled {
      pointer-events: none;
      opacity: 0.4;   }

Using readonly

    <input [readonly]="data.name === ''? true:false" type="text" value={{data.name}} >
    or
    <input [readonly]="data=== ''? true:false" type="text"  value={{data.name}}>

data is a variable which i declare in my component. Initially, in the above cases, data is null, at that time i need to make textfield as read-only

Upvotes: 2

Views: 1569

Answers (3)

Telman
Telman

Reputation: 1477

I think one of these options could work for you:

[readonly]="!data"

or

[class.inputDisabled]="!data"

Upvotes: 1

TheParam
TheParam

Reputation: 10541

Here you need to compare data with the undefined so that condition will be true and your input field will get disable based on this condition.

Example -

Using ngClass

<input type="text" [ngClass]="{'disabledDiv': !data }" 
    id="requestor_name" value={{data.name}}
    name="requestor_name">

Using readonly

<input [readonly]="!data" type="text"  value={{data.name}}>

Hope this will help

Upvotes: 0

arj
arj

Reputation: 983

this will work fine for me

<input type="text" [ngClass]="{disabledDiv: data ? false:true}" id="requestor_name" value={{data.name}}
            name="requestor_name">

Upvotes: 0

Related Questions