Angular Directive - Tuong-Nguyen/Angular-D3-Cometd GitHub Wiki
- Attach behavior to DOM elements.
- Multiple directives can be applied to the same element.
Specify which elements the directive is applied.
- Element: footer
- Class: .alert
- Attribute: [color]
- Attribute with specific value: [color=red]
- Combination of the above: footer[color=red] - [color],footer.alert - footer:not(.alert)
Note: CCS selector like descendants, siblings, ids, wildcards and pseudos (rather than :not) are not supported. Note: Do not start attribute selector with bind-, on-, let-, ref-.
-
property:binding
- property: Directive property. - binding: DOM property.
@Directive({
selector: '[loggable]',
inputs: ['text: logText']
})
export class SimpleTextDirective {
}
Text property is automatically created for SimpleTextDirective.
- For receiving change notification, we can add property setter
export class SimpleTextDirective {
set text(value) {
console.log(value);
}
}
- Use @Input decorator:
@Directive({
selector: '[loggable]'
})
export class InputDecoratorDirective {
// text: logText
@Input('logText') text: string;
// text: text with setter
@Input('text')
set text(value) {
}
// textValue: textValue with setter
@Input()
set textValue(value) {
}
}
- Note: Input is the way for Parent pass data to Child
Notify Parent from Child
- Declare @Output decorator
- Create an EventEmmiter
- Emit an event
@Component({
selector: 'ns-pony',
// the method `selectPony()` will be called on click
template: `<div (click)="selectPony()">{{ pony.name }}</div>`
})
export class SelectablePonyComponent {
@Input() pony: Pony;
// we declare the custom event as an output,
// the EventEmitter is used to emit the event
@Output() ponySelected = new EventEmitter<Pony>();
/**
* Selects a pony when the component is clicked.
* Emits a custom event.
*/
selectPony() {
this.ponySelected.emit(this.pony);
}
}
-
ngOnChanges
: called for each bound property change. (OnChanges) -
ngOnInit
: called only once after first change. (OnInit) -
ngOnDestroy
: called when component is removed. (OnDestroy)