How angular's @Attribute decorator works?
Asked Answered
G

1

15

I am new to learn Angular. I was learning about angular's decorators on angular.io. There is not much information about the @Attribute decorator. Please anyone give me some use cases.

Gushy answered 1/1, 2018 at 7:0 Comment(2)
I’ve been using Angular for years but somehow completely missed this feature. One obvious advantage is that since the value is available in the constructor you can immediate use it and don’t need to wait for ngOnInit. You could even use it in member initialization.Medan
Here is the official documentation for @Attribute angular.io/guide/attribute-binding#injecting-attribute-valuesTincture
T
17

The @Attribute decorator returns the value of the specified attribute from the host.

For example:

@Directive({
  selector: '[test]'
})
export class TestDirective {
  constructor(@Attribute('type') type ) {
    console.log(type); // text
  }
}

@Component({
  selector: 'my-app',
  template: `
    <input type="text" test>
  `,
})
export class App {}

It useful for example when you don't need to use Inputs() and you don't want Angular to recheck the value in each change detection cycle. With Attribute you are getting the value once and your are done.

Topazolite answered 1/1, 2018 at 7:5 Comment(3)
Also, as a real-life example, you can add that router-outlet uses this decorator to obtain the value of name attribute before change detection happens required in case of using @InputRegolith
I am wondering what is this rule for: codelyzer.com/rules/no-attribute-parameter-decoratorSignorino
Can I pass that value to attribute using a constant (instead of a string) by interpolation?Clockwork

© 2022 - 2024 — McMap. All rights reserved.