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.
How angular's @Attribute decorator works?
Asked Answered
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-values –
Tincture
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.
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 @Input
–
Regolith I am wondering what is this rule for: codelyzer.com/rules/no-attribute-parameter-decorator –
Signorino
Can I pass that value to attribute using a constant (instead of a string) by interpolation? –
Clockwork
© 2022 - 2024 — McMap. All rights reserved.