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 f
None of them worked for me.. Finally found solution by creating custom directive angular.. Directives are powerful feature of angular
@Directive({
selector: '[readonly],[readOnly]',
host: {
'[attr.readonly]': '_isReadonly ? "" : null'
}
})
class ReadonlyDirective {
_isReadonly = false;
@Input() set readonly (v) {
this._isReadonly = coerceBooleanProperty(v);
};
ngOnChanges(changes) {
console.log(changes);
}
}
@NgModule({
...
declarations: [ ..., ReadonlyDirective ],
...
})
<input [(ngModel)]="name" [readonly]="isReadonly" />
or
<input [(ngModel)]="name" readonly />
Demo https://stackblitz.com/edit/angular-readonly-input-aifncy?file=src/app/app.component.ts
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>
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;
You can use <input readonly="{{ variable }}>"
.
In your *.component.ts, initialize the variable:
private variable: boolean = true;