3

I'm trying to do host binding to input element's readonly attribute so that it will only be added to the host element but won't have any value assigned to it. The way that they are supposed to be used. I know that HTML spec specifically say that assigning it any value will not have any difference as long as the attribute is present.

But still. Is it possible to somehow add an attribute without a value?

What I tried

As attributes are removed when they're applied a null value I've done this trick:

@HostBinding('attr.readonly')
private _readonly: '' | null = null;
public get readonly() {
  return this._readonly !== null;
}
public set readonly(value: boolean) {
  this._readonly = value ? '' : null;
}

This will partially work because it will remove the readonly attribute from the host element when the value is null, but when the value is an empty string this will still result in readonly="", which isn't what I'm trying to do. My desired output would just be readonly without any value being applied to it.

I also tried doing the same with renderer.setAttribute but it works the same.

Is it possible then?

Here's a stackblitz to play around.

Robert Koritnik
  • 103,639
  • 52
  • 277
  • 404
  • Binding null to attribute will remove it. please check. https://stackoverflow.com/questions/36745734/how-to-add-conditional-attribute-in-angular-2 – Nour Feb 08 '18 at 09:31
  • @Nour Yeah I know... I formed that sentence a bit clumsily. I edited it a bit to clarify that `null` works as expected, but empty string still assigns a value to the attribute which is not what I want. – Robert Koritnik Feb 08 '18 at 09:42
  • So you need to remove the attribute in case of empty string also ? – Nour Feb 08 '18 at 09:56
  • No. In case of empty string I want the result to be `readonly` and not `readonly=""`. – Robert Koritnik Feb 12 '18 at 07:15
  • `readonly` and `readonly=""` are exactly the same (https://html.spec.whatwg.org/#boolean-attribute) – Steve Van Opstal Jul 26 '18 at 09:23

1 Answers1

3

You can achieve this using @HostBinding('attr.readonly') readOnly = '';

Explanation:

  • Assigning '' to attribute will only add the attribute without value.
  • Assigning null to remove the attribute.
  • Setting non-null value eg: true or yes with set the corresponding value on the attribute.
rewath
  • 41
  • 1
  • 8