Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to add an attribute to Angular host element without a value

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.

like image 865
Robert Koritnik Avatar asked Oct 21 '25 04:10

Robert Koritnik


1 Answers

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.
like image 85
rewath Avatar answered Oct 23 '25 18:10

rewath