Effective Angularの第2章の後半のまとめ
の続編
3章:Enhancing Your Applications with Directives, Pipes, and Animations
を読んだのでその感想
Directive
・ng系のdirective
ngModel:two-wayでformに使う
ngStyle:inlineのstyleに使う
ngClass:cssのclassに使う
・ElementRef
生のHTMLを触るために使う
https://zenn.dev/hashito/articles/f9b9c2401e0318
・directiveをカスタマイズ
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | @Directive({ selector: '[appHighlight]' , standalone: true , }) export class HighlightDirective implements OnInit{ private el = inject(ElementRef).nativeElement; @Input() textColor = 'white' ; @Input() backgroundColor = "black" ; ngOnInit(): void { this .el.style.color = this .textColor; this .el.style.backgroundColor = this .backgroundColor; } } |
1 | < p appHighlight [textColor]="'red'" [backgroundColor]="'green'">navbar works2!</ p > |
アクション
・@HostListener
eventをlistenする
https://zenn.dev/yusuke_docha/articles/3180ceb34ca71b
pipe
・通常
1 2 | < div >{{now | date: 'YYYY'}}</ div > < div >{{now | date | uppercase}}</ div > |
・async pipe
asyncにすると非同期動く
1 | timer: Observable<number> = interval(2000); |
1 | < div >{{timer | async}}</ div > |
・pipeをカスタマイズ
1 2 3 4 5 6 7 8 9 10 11 12 | //定義側 @Pipe({ name: 'multiply' , standalone: true , }) export class MultiplyPipe implements PipeTransform { transform(value: number, multiplier = 2): number { return value * multiplier; } } //利用側 imports: [CommonModule, RouterModule, RouterOutlet, NavbarComponent, MultiplyPipe], |
view
・@HostBinding
切り出した時にクラスを当てる
https://qiita.com/kawakawaryuryu/items/316ee19d5c0138ff7fa0
・ng系のレイアウト
ng-container:余計なタグを吐かない
ng-content:ng-contentタグの中にテンプレートの中身を展開する
ng-template:if文でテンプレートの出しわけ
https://qiita.com/shibukawa/items/c8c7fd22c1054348db3a
https://angular.jp/guide/components/content-projection
・レイアウトの出しわけ
1 2 | < div * ngIf = "showContent; else elseBlock" >show if true</ div > < ng-template #elseBlock>show if false</ ng-template > |