Categories
Angular Answers

How to read response headers from API response with Angular and TypeScript?

Sometimes, we want to read response headers from API response with Angular and TypeScript.

In this article, we’ll look at how to read response headers from API response with Angular and TypeScript.

How to read response headers from API response with Angular and TypeScript?

To read response headers from API response with Angular and TypeScript, we can set the observer option to 'response'.

For instance, we write

http.get<any>(url, { observe: "response" }).subscribe((resp) => {
  console.log(resp.headers.get("X-Token"));
});

in a method to make a GET request with http.get.

We call it with the url to make the request to and an object with the observer property set to 'response' to get the response.

In the subscribe callback, we get the response header by the key with resp.headers.get.

Conclusion

To read response headers from API response with Angular and TypeScript, we can set the observer option to 'response'.

Categories
Angular Answers

How to create a custom form input with Angular?

Sometimes, we want to create a custom form input with Angular.

In this article, we’ll look at how to create a custom form input with Angular.

How to create a custom form input with Angular?

To create a custom form input with Angular, we can create a component that implements the ControlValueAccessor class.

For instance, we write

import { Component, Provider, forwardRef, Input } from "@angular/core";
import {
  ControlValueAccessor,
  NG_VALUE_ACCESSOR,
  CORE_DIRECTIVES,
} from "@angular/common";

const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR = new Provider(NG_VALUE_ACCESSOR, {
  useExisting: forwardRef(() => InputField),
  multi: true,
});

@Component({
  selector: "inputfield",
  template: `<input [(ngModel)]="value" />`,
  directives: [CORE_DIRECTIVES],
  providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR],
})
export class InputField implements ControlValueAccessor {
  private _value: any = "";
  get value(): any {
    return this._value;
  }

  set value(v: any) {
    if (v !== this._value) {
      this._value = v;
      this.onChange(v);
    }
  }

  writeValue(value: any) {
    this._value = value;
    this.onChange(value);
  }

  onChange = (_) => {};
  onTouched = () => {};
  registerOnChange(fn: (_: any) => void): void {
    this.onChange = fn;
  }
  registerOnTouched(fn: () => void): void {
    this.onTouched = fn;
  }
}

to create the InputField class.

In it, we have a getter and setter to get the set the input value respectively.

In the template, we have an input that binds the input value to the value variable.

Also, we add the registerOnChange and registerOnTouched methods, to add the change and touch event functions.

We also set providers to [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR] so that we can use the component as a custom input that can bind to input values in template and reactive forms.

Conclusion

To create a custom form input with Angular, we can create a component that implements the ControlValueAccessor class.

Categories
Angular Answers

How to add routing with hashtag to page anchor with Angular?

Sometimes, we want to add routing with hashtag to page anchor with Angular.

In this article, we’ll look at how to add routing with hashtag to page anchor with Angular.

How to add routing with hashtag to page anchor with Angular?

To add routing with hashtag to page anchor with Angular, we can get the hash value and call scrollIntoView to scroll to the element with the given hash value as the ID.

For instance, we write

<a [routerLink]="['somepath']" fragment="Test">go to test</a>

in a template or

this._router.navigate(["/somepath", id], { fragment: "test" });

to navigate to /somepath.

The fragment property or attribute is set to the hash value.

Then in the destination component, we write

import { ActivatedRoute } from "@angular/router";

export class SearchComponent implements OnInit, AfterViewInit {
  //...
  private fragment: string;

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.route.fragment.subscribe((fragment) => {
      this.fragment = fragment;
    });
  }

  ngAfterViewInit(): void {
    try {
      document.querySelector("#" + this.fragment).scrollIntoView();
    } catch (e) {}
  }
}

to call document.querySelector("#" + this.fragment).scrollIntoView(); in ngAfterViewInit to scroll to the item with the ID equal to this.fragment.

We watch for hash value changes with

this.route.fragment.subscribe((fragment) => {
  this.fragment = fragment;
});

Conclusion

To add routing with hashtag to page anchor with Angular, we can get the hash value and call scrollIntoView to scroll to the element with the given hash value as the ID.

Categories
Angular Answers

How to fix @ViewChild annotation returns undefined with Angular?

Sometimes, we want to fix @ViewChild annotation returns undefined with Angular.

In this article, we’ll look at how to fix @ViewChild annotation returns undefined with Angular.

How to fix @ViewChild annotation returns undefined with Angular?

To fix @ViewChild annotation returns undefined with Angular, we can watch the @ViewChild for changes.

For instance, we write

import {
  Component,
  ViewChildren,
  OnInit,
  AfterViewInit,
  QueryList,
} from "@angular/core";
import { GridComponent } from "@progress/kendo-angular-grid";

export class SearchComponent implements OnInit, AfterViewInit {
  //...
  @ViewChildren("searchGrid")
  public Grids: QueryList<GridComponent>;

  private SearchGrid: GridComponent;

  public ngAfterViewInit(): void {
    this.Grids.changes.subscribe((comps: QueryList<GridComponent>) => {
      this.SearchGrid = comps.first;
    });
  }
}

to call this.Grids.changes.subscribe in ngAfterViewInit to watch for changes in the Grids @ViewChild variable.

We call it with a callback that gets the element nodes QueryList list value.

And we get the element from comps.first when it changes.

Conclusion

To fix @ViewChild annotation returns undefined with Angular, we can watch the @ViewChild for changes.

Categories
Angular Answers

How to declare a variable in a template in Angular?

Sometimes, we want to declare a variable in a template in Angular.

In this article, we’ll look at how to declare a variable in a template in Angular.

How to declare a variable in a template in Angular?

To declare a variable in a template in Angular, we can use ng-template.

For instance, we write

<ng-template
  #selfie
  [ngTemplateOutlet]="selfie"
  let-a="aVariable"
  [ngTemplateOutletContext]="{ aVariable: 123 }"
>
  <div>
    <span>{{ a }}</span>
  </div>
</ng-template>

to define the template variable a with

let-a="aVariable"

We set the variable’s value to aVariable.

And we set aVariable‘s value with

[ngTemplateOutletContext]="{ aVariable: 123 }"

Then in the span inside ng-template, we render a.

Conclusion

To declare a variable in a template in Angular, we can use ng-template.