Monday, March 15, 2021

Angular development with TypeScript note

 Angular development with TypeScript

1. source code

https://github.com/Farata/angulartypescript

forum:

https://forums.manning.com/forums/angular-development-with-typescript-2E

Although most of his books are printed, his Java Programming for Kids, Parents, and Grandparents is available for free download in several languages at http://myflex.org/books/java4kids/java4kids.htm.

2.

Angular is a component-based framework, and any Angular app is a tree of components.

A parent component can pass data to its child by binding the values to the child’s component property. A child component has no knowledge of where the data came from. A child component can pass data to its parent (without knowing who the parent is) by emitting events. This architecture makes components self-contained and reusable.

Most of the business logic of your app is implemented in services, which are classes without a UI. Angular will create instances of your service classes and will inject them into your components.

3.

You don’t need to modify dependencies in the package.json file manually. Run the ng update command, and all dependencies in package.json will be updated, assuming you have the latest version of Angular CLI installed. The process of updating your apps from one Angular version to another is described at https://update.angular.io

4.

ng g c— Generates a new component.

ng g s— Generates a new service.

ng g d— Generates a new directive.

ng g m— Generates a new module.

ng g application— Generates a new app within the same project. This command was introduced in Angular 6.

ng g library— Starting with Angular 6, you can generate a library project.

5.

For cleaner code separation, we usually don’t use a component for code that fetches or manipulates data. An injectable service is the right place for handling data. 

Note that the generated ProductService class is annotated with the @Injectable() decorator. To have Angular instantiate and inject this service into any component, add the following argument to the component’s constructor:

constructor(productService: ProductService){

  // start using the service, e.g. productService.getMyData();

}

Starting from Angular 6, provideIn: 'root' allows you to skip the step of specifying the service in the providers property of the NgModule() decorator.

6.

A directive can’t have its own UI, but can be attached to a component or a regular HTML element to change their visual representation. There are two types of directives in Angular:

Structural— The directive changes the structure of the component’s template. (like *ngFor, *ngIf)

Attribute— The directive changes the behavior or visual representation of an individual component or HTML element.

7.

Angular supports two types of data binding: unidirectional (default) and two-way. With unidirectional data binding, the data is synchronized in one direction: either from the class member variable (property) to the view or from the view event to the class variable or a method that handles the event.

Use square brackets to bind the value from a class variable to a property of an HTML element or an Angular component. 

<span [hidden]="isValid">This field is required</span>

This is unidirectional binding from the class variable to the view.

Remember, square brackets represent property binding, and parentheses represent event binding. To denote two-way binding, surround a template element’s ngModel with both square brackets and parentheses. 

[(ngModel)]="shippingAddress"

8.

In SPAs, you need the ability to modify the URL without forcing the browser to make a server-side request so the application can locate the proper view on the client. Angular offers two location strategies for implementing client-side navigation:

HashLocationStrategy. Changing any character to the right of the hash sign doesn’t cause a direct server-side request

PathLocationStrategy. This is the default location strategy in Angular.

To use hash-based navigation, @NgModule() has to include the providers value:

providers:[{provide: LocationStrategy, useClass: HashLocationStrategy}]

The <router-outlet> specifies the area on the page where the router will render the components (one at a time)


9.

By default the address bar of the browser changes as the user navigates with the router. If you don’t want to show the URL of the current route, use the skipLocationChange directive:

<a [routerLink]="['/product']" skipLocationChange>Product Details</a>


10.

A provider is an instruction to Angular about how to create an instance of an object for future injection into a target component, service, or directive. 

The long version would look like this: providers:[{provide: ProductService, useClass: ProductService}]. You say to Angular, “If you see a class with a constructor that uses the ProductService token, inject the instance of the ProductService class.”

@Injectable() is required only when the service itself has its own dependencies. It instructs Angular to generate additional metadata for this service. 

Providers declared in the @NgModule() decorator of a lazy-loaded module are available within such a module, but not to the entire application. 

providers of eagerly loaded modules are merged with providers of the root module. In other words, Angular has a single injector for all eagerly loaded modules.

11.

    of(1,2,3).subscribe(

      value=>console.log(value),

      err=>console.log(err),

      ()=>console.log("Streaming is over")

    );

    from(beers).pipe(

      map(beer=>beer.price),

      reduce((total,price)=>total+price,10)

    ).subscribe(

      beer=>console.log(beer),

      err=>console.log(err)

    );

12.

In a regular JavaScript app, to get a reference to the DOM element, you use a DOM selector API, document.querySelector(). In Angular, you can use the @ViewChild() decorator to get a reference to an element from a component template.

 <input type="text" #stockSymbol placeholder="Enter stock" >

   @ViewChild('stockSymbol') myInputField: ElementRef;

  constructor(){

  }

  ngAfterViewInit(): void {

    let keyup$ = fromEvent(this.myInputField.nativeElement, 'keyup');

    let keyupValue$ = keyup$.pipe(

      debounceTime(500),

      map(event => event['target'].value)

    ).subscribe(

      stock => this.getStockQuoteFromServer(stock)

    );

  }


  getStockQuoteFromServer(stock: string) {

    console.log(`The price of ${stock} is ${(100 * Math.random()).toFixed(4)}`);

  }

13.

In Angular, HTTP requests return observables. 

Angular doesn’t offer an API to support event bubbling. If event bubbling is important to your app, don’t use EventEmitter; use native DOM events instead.

14.

There are two approaches to working with forms in Angular: template-driven and reactive. 

Because you’re limited to HTML syntax while defining the form, the template-driven approach suits only simple forms.

With the reactive API, You construct the form model object explicitly using the FormControl, FormGroup, and FormArray classes.

To enable reactive forms, add ReactiveFormsModule from @angular/forms to the imports list of NgModule. For template-driven forms, import FormsModule

15.

NgForm is the directive that represents the entire form. It’s automatically attached to every <form> element.

16.

FormControl is an atomic form unit. FormGroup is a collection of FormControl objects and represents either the entire form or its part. When you need to programmatically add (or remove) controls to a form, use FormArray. It’s similar to FormGroup but has a length variable.

17.

[ngModelOptions]= "{updateOn:'blur'}" change/submit

18.

To notify BehaviorSubject about the new value, you use next(), and to notify the store about the new state, you use dispatch(). To get the new state, subscribe to the observable in both cases.

In ngrx apps, the Store service always remains a single source of truth, which may have multiple slices of state.

even though actions can be handled in both a reducer and an effect, only a reducer can change the state of an app.

No comments:

Post a Comment