I came across angular components with this property: [@property_name] (with an at sign at the beginning).
What is this and what is it used for? How is it different from a regular [property_name] binding without the @?
CodePudding user response:
From Angular doc Defining animations and attaching them to the HTML template:
When you've defined an animation trigger for a component, attach it to an element in that component's template by wrapping the trigger name in brackets and preceding it with an
@symbol.
html <div [@triggerName]="expression">...</div>;
Further borrowing the example from the docs:
@Component({
selector: 'app-open-close',
animations: [
trigger('openClose', [
state('open', style({
height: '200px',
opacity: 1,
backgroundColor: 'yellow'
})),
state('closed', style({
height: '100px',
opacity: 0.8,
backgroundColor: 'blue'
})),
transition('open => closed', [
animate('1s')
]),
transition('closed => open', [
animate('0.5s')
])
]),
],
templateUrl: 'open-close.component.html',
styleUrls: ['open-close.component.css']
})
export class OpenCloseComponent {
isOpen = true;
toggle() {
this.isOpen = !this.isOpen;
}
}
<nav>
<button (click)="toggle()">Toggle Open/Close</button>
</nav>
<div [@openClose]="isOpen ? 'open' : 'closed'" >
<p>The box is now {{ isOpen ? 'Open' : 'Closed' }}!</p>
</div>
In the above example, the animation trigger openClose has two states 'open' and 'closed' which are controlled by adjusting the boolean variable isOpen.
CodePudding user response:
These are all possible places where @ can be used in Angular that I know:
- Decorators:
- Class decorators: When you to declare something as Module, Component, Directive, Injectable or Pipe.
- Property decorators: When you use declare component's property as
@Input,@Output,@ViewChild... - Method decorators: When you use
@HostListener
- Animations
- When you want to trigger a state of the animation in your template file. For example
[@collapse]="!menu.collapsed".
- Media Query
- This is not Angular specific, but it can also be found in the code. You use
@mediaCSS property to define specific styles based on screen size.
CodePudding user response:
Could be a number of things, most commonly it's a decorator. Probably you've seen @Component right? Well it's a directive. https://www.sitepoint.com/javascript-decorators-what-they-are/ Angular makes heavy use of them, heck you can make your own custom decorators too. Their a way to give special meaning to a function, to define something and many things in between but most importantly it's just syntax to make code more readable, manageable and understandable. Under the hood it's code that you can apply over some other piece of code.
