I have just started working with Angular 2.
I was wondering what are the differences between components and directives in Angular 2?
I have just started working with Angular 2.
I was wondering what are the differences between components and directives in Angular 2?
Basically there are three types of directives in Angular2 according to documentation.
It is also a type of directive with template,styles and logic part which is most famous type of directive among all in Angular2. In this type of directive you can use other directives whether it is custom or builtin in the @Component
annotation like following:
@Component({
selector: "my-app"
directives: [custom_directive_here]
})
Use this directive in your view as:
<my-app></my-app>
For the component directive i have found best tutorial here.
Like *ngFor
and *ngIf
, used to change the DOM layout by adding and removing DOM elements. explained here
They are used to give custom behavior or style to the existing elements by applying some functions/logic. Like ngStyle
is an attribute directive to give style dynamically to the elements. We can create our own directive and use this as attribute of some predefined or custom elements, here is the example of a simple directive:
Firstly we have to import directive from @angular/core
import {Directive, ElementRef, Renderer, Input} from '@angular/core';
@Directive({
selector: '[Icheck]',
})
export class RadioCheckbox {
// custom logic here...
}
We can use this in the view as shown below:
<span Icheck>HEllo Directive</span>
For more info you can read the official tutorial here and here
Components have their own view (HTML and styles). Directives are just "behavior" added to existing elements and components.
Component
extends Directive
.
Because of that there can only be one component on a host element, but multiple directives.
Structural directives are directives applied to <template>
elements and used to add/remove content (stamp the template).
The *
in directive applications like *ngIf
causes a <template>
tag to be created implicitly.
Here is the actual definition.
Any other definition is wrong.
To complete what Günter said, we can distinguish two kinds of directives:
NgFor
and NgIf
. These ones are linked to the template concept and must be prefixed by an *
. See the section "Templates and *" in this link for more details: http://victorsavkin.com/post/119943127151/angular-2-template-syntaxHope it helps you, Thierry
A component is a directive with an associated view (i.e. HTML to be rendered). All components are directives, but not all directives are components. There are three types of directives:
*ngIf
which can insert or remove an DOM element (or angular component which is a custom DOM element, but still a DOM element).import { Component, HostListener, HostBinding, Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
}
@Component({
selector: 'app-root',
template: `
<div *ngIf='myBool' appHighlight>Hi there</div>
`,
styleUrls: ['./app.component.scss'],
})
export class AppComponent {
myBool:boolean = true;
}
In the above example we can observe the following:
AppComponent
has a template with a <div>
element which displays, hi there.<div>
element. This means it will manipulate the behaviour of the <div>
element. In this case it will highlight the text and will turn it yellow.*ngIf
is also located on the <div>
element and will determine if the element is to be inserted. The <div>
will be conditionally shown depending on whether the expression myBool
can be coerced to true
.Angular 2 follows component/Service model of architecture.
An angular 2 Application is made of components. A component is the combination of an HTML template and a component class (A typescript class ) that controls a portion of the screen.
For the good practice, component class is used for data binding to the respective view. Two way data binding is a great feature provided by angular framework.
Components are reusable across your application using selector name provided.
Component is also a kind of directive with a template.
Other two directives are
Structural directives—change the DOM layout by adding and removing DOM elements. Ex: NgFor
and NgIf
.
Attribute directives—change the appearance or behavior of an element, component, or another directive. Ex: NgStyle
Actually components are also directives, but have differences between them.
Attribute Directives :
Attribute directives are classes that are able to modify the behavior or appearance of a single element. For creating an attribute directive apply the @Directive
to a class.
import { Directive, ElementRef } from "@angular/core";
@Directive({
selector: "[custom-attr]", })
export class CustomAttrDirective {
constructor(element: ElementRef) {
element.nativeElement.classList.add("bg-success", "text-white");
}
}
Adding a directive attribute template.html File
<tr *ngFor="let item of getProducts(); let i = index" custom-attr>
<td>{{i + 1}}</td>
<td>{{item.name}}</td>
</tr>
Structural Directives :
Structural directives change the layout of the HTML document by adding and removing elements, as a micro-templates. Structural directives allow content to be added conditionally based on the result of an expression such as*ngIf
or for the same content to be repeated for each object in a data source such as *ngFor
.
You can use the built-in directives for common tasks, but writing custom structural directives provides ability to tailor behavior to your application.
<p *ngIf="true">
Expression is true and ngIf is true.
This paragraph is in the DOM.
</p>
<p *ngIf="false">
Expression is false and ngIf is false.
This paragraph is not in the DOM.
</p>
Components :
Components are directives that their own templates, rather than relying on content provided from elsewhere. Components have access to all directive features, still have a host element, can still define input and output properties, and so on.But they also define their own content.
It can be easy to underestimate the importance of the template, but attribute and structural directives have limitations. Directives can do useful and powerful work, but they don’t have much insight into the elements they are applied to. Directives are most useful when they are general-purpose tools, such the ngModel
directive, which can be applied to any data model property and any form element, without regard to what the data or the element is being used for.
Components, by contrast, are closely tied to the contents of their templates. Components provide the data and logic that will be used by the data bindings that are applied to the HTML elements in the template, which provide the context used to evaluate data binding expressions and act as the glue between the directives and the rest of the application. Components are also a useful tool in allowing large Angular projects to be broken up into manageable chunks.
import { Component, Input } from '@angular/core';
import { Hero } from './hero';
@Component({
selector: 'app-hero-child',
template: `
<h3>{{hero.name}} says:</h3>
<p>I, {{hero.name}}, am at your service, {{masterName}}.</p>
`
})
export class HeroChildComponent {
@Input() hero: Hero;
@Input('master') masterName: string;
}
Do not confuse the question with mentioning types of a directive or anything unrelated. One here only want to know the exact difference between a directive and a component so let me tell what exactly that is:
A directive is a reusable piece of code which performs a specific functionality but not contain any TEMPLATE(html), can't take arguments or callbacks
where a component does the same but have it's own independent TEMPLATE(html) and can take dynamic arguments as props, callbacks and can generate dynamic markup on the basis of this.
Both can be used with the name of their selectors.
© 2022 - 2024 — McMap. All rights reserved.