Tuesday 20 October 2020

Implementing ControlValueAccessor


import { Component, forwardRef, Input, OnInit } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Component({
  selector: 'app-password-input',
  templateUrl: './password-input.component.html',
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => PasswordInputComponent),
      multi: true
    }
  ]
})
export class PasswordInputComponent implements OnInit, ControlValueAccessor {
  constructor() {}
  writeValue(obj: any): void {
    this.Value = obj;
  }
  registerOnChange(fn: any): void {
    this.onChange = fn;
  }
  registerOnTouched(fn: any): void {
    this.onTouch = fn;
  }
  setDisabledState?(isDisabled: boolean): void {
    this.disabled = isDisabled;
  }
  onChange: any = () => {};
  onTouch: any = () => {};
  disabled?: boolean;
  ngOnInit(): void {}

  /** Password value */
  public value: string;
  set Value(val) {
    // this value is updated by programmatic changes
    if (val !== undefined && this.value !== val) {
      this.value = val;
      this.onChange(val);
      this.onTouch(val);
    }
  }
  get Value(): string {
    return this.value;
  }
 }

Thursday 1 October 2020

Custom Events with Angular Elements

Created component in Angular, it has Output called selectedStep, that emits a number.
@Output() public selectedStep: EventEmitter<number> = new EventEmitter<number>();
How to write CustomEvent in plain HTML + JS page, so that it would eg. display step number to console?
<script>
// trigger this function, when event is emitted from inside custom-element
function stepChanged(e) {
  console.log('Current step: ' + e);
}

document.addEventListener("DOMContentLoaded", function() {
  // Handler when the DOM is fully loaded
  let element = document.querySelector("custom-element");
  element.addEventListener("selectedStep", event => {
    stepChanged(event.detail);
  });
});

</script>
<custom-element></custom-element>
Important to remember: 
  1. addEventListener first parameter is the name of Output 
  2. Emitted value is in detail property of second paramenter