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

走远了吗. 提交于 2019-12-03 01:15:07

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>

You can use <input readonly="{{ variable }}>".

In your *.component.ts, initialize the variable:

private variable: boolean = true;

All depends on what you want to achieve. At first look, I would say that pct. 2 is the simplest way to do it:

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

Then, on your component you declare the variable:

isReadOnly: boolean;

After, you assign the value as you wish:

// when you want to be read-only
isReadOnly = true;
// whe you want to be editable
isReadOnly = false;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!