I have seen @Attribute() being used in Directives usually as a parameter in the constructor like this:
export class EqualValidator implements Validator {
constructor( @Attribute(‘validateEqual’) public validateEqual: string) {}
validate(c: AbstractControl): { [key: string]: any } {}
}
and @Input() used in Components like this:
export class UserProfile {
@Input() user;
constructor() {}
}
And then you can pass data into these variables in the template with property binding in the case of @Input().
What are the main differences between these decorators and when should you use them?
In a simple way, transform/exchange data between two components. In this article, I am exploring two very important points, related to Angular 2 + version, which the part of Parameter Decorator and these points are called @Input and @Output decorators .
@Inoput decorator is used to pass data (property binding) from parent to child component. The component property should be annotated with @Input decorator to act as input property. Let's explore it practically. I have created an angular application which is AngApp.
Both Decorators and Annotations are supported by Angular. This is a legacy thing because Angular2 swapped from AtScript to TypeScript. Decorators are the default in AngularJs but you can use Annotations too.
For these two components to communicate to each other, we need both the @Ouput and @Input decorators provided by Angular. Now, these two decorators have distinct functions: @Ouput - A decorator that lets the child component communicates with the parent component. @Input - A decorator that allows the parent to communicates with the child component.
@Input(): Used to pass values into the directive or to pass data from one component to another (typically parent to child).
@Attribute(): You are able to retrieve the constant value of an attribute available in the host element of component/directive and it has to be used with a parameter of a component’s or Directive’s constructor
Hope this help!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With