title: Pass required to custom component Angular
body: <p>I have a custom component to use for phone numbers</p>
  
  <p>I need to use the required flag for it</p>
  
  <p>Here is HTML of component</p>
  
  <pre><code>  &lt;form #phoneForm="ngForm" novalidate name="PhoneForm"&gt;
      &lt;div class="form-row"&gt;
          &lt;div class="form-group col-md-3"&gt;
             &lt;p-dropdown
                #phoneCodeInput = ngModel
                [disabled]="!countrycodes.length"
                [options]="countrycodes"
                autoWidth="false"
                [(ngModel)]="phoneCode"
                (ngModelChange)="onNumberChange()"
                [style]="{ width: '100%', height: '100%'}"
                name="countryCodes"
                [autoWidth]="true"
              &gt;&lt;/p-dropdown&gt;
          &lt;/div&gt;
          &lt;div class="form-group col-md-9"&gt;
          &lt;input
              [readonly] = "isReadOnly"
              #phoneNumberInput = ngModel
              number-directive
              class="form-control"
              placeholder="Enter phone number"
              [required] = "isFieldRequired"
              [(ngModel)]="phoneNumber"
              (ngModelChange)="onNumberChange()"
              class="form-control"
              type="text"
              name="name"
              maxlength="11"
          /&gt;
          &lt;/div&gt;
      &lt;/div&gt;
      &lt;validation-messages [formCtrl]="phoneNumberInput"&gt;&lt;/validation-messages&gt;
    &lt;/form&gt;
  </code></pre>
  
  <p>Here is a typescript code of the component, where I use the Input parameter to make validation</p>
  
  <pre><code>import { AppComponentBase } from '@shared/common/app-component-base';
  import {
      Component,
      OnInit,
      Injector,
      AfterContentChecked,
      ViewChild,
      forwardRef,
      Input,
  } from '@angular/core';
  import * as lookup from 'country-telephone-data';
  import { SelectItem } from 'primeng/api';
  import { ControlValueAccessor, ValidationErrors, NG_VALUE_ACCESSOR, NG_VALIDATORS } from '@angular/forms';
  
  
  @Component({
      selector: 'phone-number',
      templateUrl: './phone-number.component.html',
      providers: [
          { provide: NG_VALUE_ACCESSOR, useExisting: PhoneNumberComponent, multi: true },
          {
              provide: NG_VALIDATORS,
              useExisting: forwardRef(() =&gt; PhoneNumberComponent),
              multi: true
          }
      ]
  })
  export class PhoneNumberComponent extends AppComponentBase
      implements OnInit, ControlValueAccessor, AfterContentChecked {
      @Input() isRequired: boolean;
      @ViewChild('phoneForm') phoneForm;
      constructor(injector: Injector) {
          super(injector);
      }
      countrycodes: SelectItem[] = [];
      phoneCode: string;
      phoneNumber: string;
      required: string | boolean;
      isFieldRequired: boolean = false;
      isReadOnly: boolean = false;
  
      private changed = [];
      private touched = [];
  
      disabled: boolean;
  
  
      ngAfterContentChecked(): void {
          this.checkValidity();
      }
  
      checkValidity(): void {}
      propagateChange = (_: any) =&gt; {};
  
      get phoneNumberResult(): string {
          const result = `${this.phoneCode ? this.phoneCode : ''} ${
              this.phoneNumber ? this.phoneNumber : ''
          }`;
          return result;
      }
  
      set phoneNumberResult(value: string) {
          if (this.phoneNumberResult !== value) {
              const [phoneCode, phoneNumber] = value.split(' ');
              this.phoneCode = phoneCode;
              this.phoneNumber = phoneNumber;
              this.changed.forEach(f =&gt; f(value));
          }
      }
  
      writeValue(obj: string): void {
              this.phoneNumberResult = obj ? obj : '+44';
      }
      registerOnChange(fn: any): void {
          this.propagateChange = fn;
      }
      registerOnTouched(fn: any): void {
          this.touched.push(fn);
      }
      setDisabledState?(isDisabled: boolean): void {
          this.disabled = isDisabled;
      }
  
  
      ngOnInit(): void {
          if (this.isRequired === true) {
              this.isFieldRequired = true;
          }
          lookup.allCountries.forEach(element =&gt; {
              this.countrycodes.push({
                  label: `+${element.dialCode}`,
                  value: `+${element.dialCode}`,
              });
          });
      }
  
      onNumberChange(): void {
          this.propagateChange(this.phoneNumberResult);
      }
  
  
      validate(): ValidationErrors {
          if (!this.phoneForm.valid) {
              return { message: 'custom error' };
          }
          return null;
      }
  
      registerOnValidatorChange(fn: () =&gt; void): void {
          this.checkValidity = fn;
      }
  }
  </code></pre>
  
  <p>Now I use input parameters to implement the required functionality</p>
  
  <p>here is how I use my component now</p>
  
  <pre><code>&lt;phone-number [isRequired] =" isMobileNumberRequired" id="" #mobileEdit name="mobile" [(ngModel)]="tenant.mobileNumber" (ngModelChange)="onMobileChanged()"&gt;&lt;/phone-number&gt;
  </code></pre>
  
  <p>I need to use just <code>required</code> flag at component call instead of passing parameters. How I can do it? </p>