3

There is a post on Set Attribute Without value which provides a good solution using $('body').attr('data-body','');

However, in my current ionic project, I am using Angular's Renderer2 API to manipulate DOM, and I have a requirement to create a button dynamically and also to set ion-button as one of the attributes.

I am able to set the attributes which are having value with the below code, but not getting any luck in figuring out how to add the attribute without the value.

// Make Copy Button functional
   this.renderer.setAttribute(code, 'id', 'copy-target');
   this.renderer.addClass(button, 'copy-button');
   this.renderer.setAttribute(button, 'data-clipboard-action', 'copy');
   this.renderer.setAttribute(button, 'data-clipboard-target', '#copy-target');

   this.renderer.setAttribute(button, 'ion-button', null); // this doesn't work.

Any guidance is appreciated.

6
  • What about this.renderer.setAttribute(button, 'ion-button', ''); ? Commented Jul 23, 2018 at 7:12
  • setAttribute requires el: any, name: string, value: string, namespace?: string the null must be a string. perhaps just add an empty string and see if it has the expected behavior ''. Commented Jul 23, 2018 at 7:13
  • Null is a string too though. Commented Jul 23, 2018 at 7:25
  • @Grenther I tried 3 options '', null, and not giving any option at all. Still no luck. When I don't pass 3rd argument it comes as undefined. Commented Jul 23, 2018 at 7:26
  • @ritaj technically it's not a string 'Null' would be a string. Null may be used instead of a string in certain conditions tho. Commented Jul 23, 2018 at 7:29

1 Answer 1

2

You should just pass an empty string. I just tried:

this.r.setAttribute(this.div.nativeElement, "ion-button", "");

On

@ViewChild("div") div: ElementRef;

And got

<div _ngcontent-c0="" ion-button="">Divara</div>

Which is the same as

<div _ngcontent-c0="" ion-button>Divara</div>

Chrome even renders it like that in developer tools:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.