Learn Some Angular Code And Tricks

Introduction

 
In this article, we are going to learn some Angular code and tricks.
 
When projecting content in Angular you can use a CSS styles selector to select the projected component. ⠀
 
For example, the project uses the .header class in the below code.
  1. import { Component, OnInit,Input } from '@angular/core';  
  2. @Component({  
  3.    selector: "lib-testlibrary",  
  4.    template: `<div class="header">  
  5.    <ng-content select=".header" ></ng-content>  
  6.    </div>`,  
  7.    styles: [  
  8. `       .header { color: blue}`  
  9.    ]  
  10. })  
  11. export class TestlibraryComponent implements OnInit {  
  12. constructor() { }  
  13.    ngOnInit(): void {}  
  14. }  
 
In the ng-content tag inside we able to use all CSS styles like, h1,h2,p,span….etc in the select.
 
Next, we are going to see @angular-extensions/pretty-html-log
 
The updated angular version improved the debugging of the angular component tests. It will be adding a console.logNgHTML method. This method to print the inner HTML of the l ComponentFixture l DebugElement l NativeElement l HTML String l Print Angular comments l Print Angular theme
 
Log the content innerHTML of a fixture:
  1. console.logNgHTML(fixture);   
DebugElement (or multiple debugElements)
  1. console.logNgHTML(fixture.debugElement);   
NativeElement (or multiple nativeElements)
  1. console.logNgHTML(fixture.debugElement.nativeElement);  
Simple HTML string
  1. console.logNgHTML('<p>Test Sat</p>');   
Print Angular comments
 
Angular adds some commands in our angular HTML file. When debugging our test, changes not printed at the time we will pass the addition flag to logNgHTML.
 
console.logNgHTML(fixture,true);
 
Print Angular theme
 
In the log, we are able to changes the theme using @angular-extensions/pretty-html-log to print the HTML themes in different ways
 
The pretty-html-log file importted from base library @angular-extensions/pretty-html-log .
  1. import { THEMES } from 'pretty-html-log';  
  2. console.logNgHTML(fixture, false, THEMES.VSCODE);  
The next one is Angular Lazy loading
 
Did you know that you can use the Angular schematics to create a lazy loaded feature in the module using the below command?
 
ng g m features/sat --route sat --module app.module.ts
 
 
After executing this command, lazy loading will be created inside the src folder.
 
Inside the file routing, a module, component, and HTML file were created.
 
The Final one is Decorators
 
Angular allows you to combine multiple Decorators on a class field
 
For example:
  1. export class SatComponent implements OnInit {  
  2.    @HostBinding('class.readonly') @Input() readonly=false;  
  3.    constructor() { }  
  4.    ngOnInit(): void { }  
  5. }  
Here we accept the read-only property as an Input and reflect it with a read-only class to the Host element.
 
I hope this article was helpful!


Similar Articles