Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the main difference between the decorators @Input() and @Attribute() in Angular2?

Tags:

angular

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?

like image 229
Alex Avatar asked Feb 13 '17 18:02

Alex


People also ask

What is @input and @output decorators in Angular 2 +?

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 .

What is the use of @inoput decorator in angular?

@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.

What is the difference between decorators and annotations in angular?

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.

How to communicate between two components in Angular 2?

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.


1 Answers

@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!

like image 106
Ha Hoang Avatar answered Sep 18 '22 17:09

Ha Hoang