Categories
Angular Answers

How to use @ViewChild in *ngIf with Angular?

Sometimes, we want to use @ViewChild in *ngIf with Angular.

In this article, we’ll look at how to use @ViewChild in *ngIf with Angular.

How to use @ViewChild in *ngIf with Angular?

To use @ViewChild in *ngIf with Angular, we set the static option to false and use a setter.

For instance, we write

<div id="layout" *ngIf="display">
  <div #contentPlaceholder></div>
</div>

to add a div with ref contentPlaceholder in the div that’s displayed when display is true.

Then in our component code, we write

export class AppComponent {
  display = false;
  private contentPlaceholder: ElementRef;

  @ViewChild("contentPlaceholder") set content(content: ElementRef) {
    if (content) {
      this.contentPlaceholder = content;
    }
  }
}

to add the setter by add a function after set.

Then when content, which is the element with the ref is defined, we set this.contentPlaceholder to content.

In Angular 8 or later, we add the static option by writing

export class AppComponent {
  display = false;
  private contentPlaceholder: ElementRef;

  @ViewChild("contentPlaceholder", { static: false }) set content(
    content: ElementRef
  ) {
    if (content) {
      // initially setter gets called with undefined
      this.contentPlaceholder = content;
    }
  }
}

to set static to false to watch for changes with the setter.

Conclusion

To use @ViewChild in *ngIf with Angular, we set the static option to false and use a setter.

Categories
Angular Answers

How to get current value of RxJS Subject or Observable?

Sometimes, we want to get current value of RxJS Subject or Observable.

In this article, we’ll look at how to get current value of RxJS Subject or Observable.

How to get current value of RxJS Subject or Observable?

To get current value of RxJS Subject or Observable, we can use the first method.

For instance, we write

const observable = of("foo");

const hasValue = (value: any) => {
  return value !== null && value !== undefined;
};

const getValue = <T>(observable: Observable<T>): Promise<T> => {
  return observable.pipe(filter(hasValue), first()).toPromise();
};


//...

to create an of observable.

Then we create the getValue function that calls observable.pipe with the filter and first operators to get the first value from the observable that isn’t null or undefined.

And then we call toPromise to return a promise with the value returned by the observable.

Then in an async function, we write

const result = await getValue(observable);

to get the value.

Conclusion

To get current value of RxJS Subject or Observable, we can use the first method.

Categories
Angular Answers

How to use pipes within ngModel on input elements in Angular?

Sometimes, we want to use pipes within ngModel on input elements in Angular.

In this article, we’ll look at how to use pipes within ngModel on input elements in Angular.

How to use pipes within ngModel on input elements in Angular?

To use pipes within ngModel on input elements in Angular, we can use separate [(ngModel)] into [ngModel] and (ngModelChange).

For instance, we write

<input
  [ngModel]="item.value | useMyPipeToFormatThatValue"
  (ngModelChange)="item.value = $event"
  name="inputField"
  type="text"
/>

to apply the useMyPipeToFormatThatValue pipe to item.value in ngModel.

Then we handle our input change events in ngModelChange.

This is because we can’t use template expression operators in template statements, which are directives that are wrapped in parentheses.

Conclusion

To use pipes within ngModel on input elements in Angular, we can use separate [(ngModel)] into [ngModel] and (ngModelChange).

Categories
Angular Answers

How to set the src attribute of an iframe without causing the unsafe value exception in Angular?

Sometimes, we want to set the src attribute of an iframe without causing the unsafe value exception in Angular.

In this article, we’ll look at how to set the src attribute of an iframe without causing the unsafe value exception in Angular.

How to set the src attribute of an iframe without causing the unsafe value exception in Angular?

To set the src attribute of an iframe without causing the unsafe value exception in Angular, we can create our own pipe that calls bypassSecurityTrustResourceUrl.

For instance, we write

import { Pipe, PipeTransform } from "@angular/core";
import { DomSanitizer } from "@angular/platform-browser";

@Pipe({ name: "safe" })
export class SafePipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer) {}
  transform(url) {
    return this.sanitizer.bypassSecurityTrustResourceUrl(url);
  }
}

to create SafePipe pipe class.

In it, we have the transform method that calls this.sanitizer.bypassSecurityTrustResourceUrl with url to make Angular ignore safety checks on the url.

The in we add SafePipe into our NgModule with

@NgModule({
  declarations: [
    //...
    SafePipe,
  ],
})
class Foo {
  //...
}

Then we can use it by writing

<iframe width="100%" height="300" [src]="url | safe"></iframe>

in our template.

We use the name value of the pipe to use it.

Conclusion

To set the src attribute of an iframe without causing the unsafe value exception in Angular, we can create our own pipe that calls bypassSecurityTrustResourceUrl.

Categories
Angular Answers

How to proxy API requests to another server with angular-cli server?

Sometimes, we want to proxy API requests to another server with angular-cli server.

In this article, we’ll look at how to proxy API requests to another server with angular-cli server.

How to proxy API requests to another server with angular-cli server?

To proxy API requests to another server with angular-cli server, we can create a proxy.config.json file with a few settings.

For instance, we write

{
  "/api": {
    "target": "http://api.foo.com",
    "secure": false
  }
}

to proxy the /api URL to http://api.foo.com in proxy.config.json.

Then in angular.json, we add

{
  //...
  "architect": {
    "serve": {
      "builder": "@angular-devkit/build-angular:dev-server",
      "options": {
        "browserTarget": "your-application-name:build",
        "proxyConfig": "src/proxy.conf.json"
      }
    }
  }
  //...
}

to add the architect property with the proxy.conf.json that we added set as the value of proxyConfig.

Then we can run ng server as usual to use the proxy config.

Conclusion

To proxy API requests to another server with angular-cli server, we can create a proxy.config.json file with a few settings.