1

I've started learning Angular recently one problem very simple (I think) which I can't find a solution is the following one:

I want to create a Component with a custom attribute without a value. Like this one:

<h1 attribute-without-value > Text <h1>

I tried in a different way but still, I don't have what I want.
I'm able to create an attribute with a value using this syntax: [attr.attr-with-value]="value" but not without.
Here some of my experiment (ref: https://stackblitz.com/edit/angular-sn94cl?embed=1&file=src/app/app.component.ts):

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template:  `
              <h1 {{nameAttr}} > doesn\'t work <h1>
              <h1 [attr.nameAttr] > also this doesn\'t work <h1>
              `,
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  nameAttr = 'attribute-without-value';
}

How can I do?

3
  • 1
    I guess the question is; why? Commented Mar 26, 2020 at 16:58
  • Your original code <h1 attribute-without-value > should work and add the attribute, as shown in this stackblitz. Do you need the attribute name to be dynamic? Commented Mar 26, 2020 at 17:18
  • yes I want it dynamic :) Commented Oct 6, 2021 at 14:28

3 Answers 3

1

I think you are actually looking for directives not components

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

Comments

0

The string interpolation {{}} should be placed inside the text area of the h1 element.

<h1> {{nameAttr}} <h1>

If you don't want it to have a value, you can just set nameAttr to '' or null.

Or if you're trying to pass a value INTO a component without a value, then you'll have to create a 2nd component, one you can pass the data to. Mapping component attributes without a value

1 Comment

I want a dom element with an attribute not an element with textContent
0

Try a directive. The way you try to do it it won't work.

https://angular.io/guide/attribute-directives

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.