I have just started working with Angular 2.
I was wondering what are the differences between components and directives in Angular 2?
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: `
Hi there
`,
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 element which displays, hi there.
- The attribute directive HighlightDirective is located on the
element. This means it will manipulate the behaviour of the element. In this case it will highlight the text and will turn it yellow.
- The structural directive
*ngIf is also located on the element and will determine if the element is to be inserted. The will be conditionally shown depending on whether the expression myBool can be coerced to true.
- 热议问题