DEV Community

Wellington Domiciano
Wellington Domiciano

Posted on • Edited on • Originally published at wldomiciano.com

2

How to use @Attribute decorator in Angular

Clique aqui para ler em Português.

The @Attribute decorator allows passing data from a parent to a child component in a way very similar to the @Input decorator.

But @Attribute is very limited in comparison to @Input as it only allows passing simple static string data.

How to use

First, you must decorate a constructor parameter.

In the code below I used the readonly keyword just as a preference matter, your parameter doesn’t need to be read-only and you can use any access modifier you want.

@Component({
  selector: "app-hello",
  template: `{{ parameter }}`,
})
export class HelloComponent {
  constructor(@Attribute("message") readonly parameter: string) {}
}
Enter fullscreen mode Exit fullscreen mode

So you can pass a static string as a normal HTML attribute. Note that the attribute name must be the same as the argument passed to @Attribute.

@Component({
  selector: "app-root",
  template: `<app-hello message="Hello"></app-hello>`,
})
export class AppComponent {}
Enter fullscreen mode Exit fullscreen mode

How DO NOT use

You cannot use data binding with @Attribute. The code below shows four WRONG ways to use this decorator.

@Component({
  selector: "app-root",
  template: `
    <app-hello [attr.message]="'Hello'"></app-hello>
    <app-hello [message]="'Hello'"></app-hello>
    <app-hello message="{{ hello }}"></app-hello>
    <app-hello [message]="hello"></app-hello>
  `,
})
export class AppComponent {
  hello = "World";
}
Enter fullscreen mode Exit fullscreen mode

Final thoughts

Although the @Input decorator is more flexible, sometimes a simple static string may be more suitable. In these times the @Attribute decorator may be very useful.

I hope this article was helpful.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay