Published on: 2024-03-28
Example Directive to apply a css class on click:
import { Directive, HostBinding, HostListener } from '@angular/core';
@Directive({
selector: '[appDropdown]',
})
export class DropdownDirective {
@HostBinding('class.open') isOpen = false;
@HostListener('click') toggleOpen() {
this.isOpen = !this.isOpen;
}
}
Components can emit their own custom events, so that other components which use it can listen to this custom events, potentially also receiving their passed data.
In the emitting component:
import { Component, EventEmitter, Output } from "@angular/core";
@Component({
selector: "app-button-click",
templateUrl: "./button-click.component.html",
styleUrl: "./button-click.component.css",
})
export class ButtonClickComponent {
@Output() // makes the custom event usable by other components
buttonClicked = new EventEmitter<string>();
onButtonClick() {
this.buttonClicked.emit("data");
}
}
The Component using the emitting component:
<div class="row">
<div class="col-xs-10">
<app-button-click (buttonClicked)="onButtonClicked($event)" />
</div>
</div>
@Component({
selector: "my-other.component",
templateUrl: "./my-other.component.html",
styleUrl: "./my-other.component.css",
})
export class MyOtherComponent {
onButtonClcked(data: string) {
console.log(data);
}
}
<div class="row">
<div class="col-xs-10">
<a
[routerLink]="['/somepath', 123, 'update']"
[queryParams]="{ showall: true }"
fragment="foo"
class="list-group-item"
>
Some Link
</a>
</div>
</div>
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-some',
templateUrl: './some.component.html',
styleUrls: ['./some.component.css'],
})
export class SomeComponent {
constructor(private router: Router) { }
onLinkClicked(id: number) {
this.router.navigate(
['/somewhere', id, 'foo'],
{queryParams: {showall: true}},
fragment: 'foo'
)
}
}