0

How can i set a formControlName in a subcomponent to optional? I will like to use ComponentA in ComponentB without a FormGroup but also in some other Components with Formgroup. Is there a possibility?

ComponentA

<app-quantity-counter
            [value]="cartItem.amount"
            [step]="1"
            [min]="1"
            [max]="1000"
            (onCounterChange)="onQuantityChange($event, cartItem)"
            controlName="amount"
          ></app-quantity-counter>

ComponentA_TS

viewProviders: [
{
  provide: ControlContainer,
  useExisting: FormGroupDirective,
},
 ],
 export class QuantityCounterComponent implements OnInit {
 @Input() controlName: string = null;
....

ComponentB

<div class="quantity-counter" [class.sm]="small">
   <!-- <button type="button" (click)="decrement()"><mat-icon class="text-muted">indeterminate_check_box</mat-icon></button>   -->
    <button type="button" (click)="decrement()">
      <mat-icon class="text-muted">keyboard_arrow_down</mat-icon>
    </button>
   <input
type="text"
[value]="value"
[(ngModel)]="value"
(blur)="onBlur()"
(keypress)="keyPress($event)"
[formControlName]="controlName"
  />
    <button type="button" (click)="increment()">
    <mat-icon class="text-muted">keyboard_arrow_up</mat-icon>
      </button>
       <!-- <button type="button" (click)="increment()"><mat-icon class="text-muted">add_box</mat-icon></button>  -->
       </div>
Michael Mitch
  • 403
  • 2
  • 7
  • 17
  • If you use it in a `FormGroup` you will use it otherwise no? Are you trying to create a custom input control? – Francesco Lisandro Apr 18 '21 at 00:55
  • In Component-B i use the with formGroup.. but e.g in Component-C i like to used it without formgroup – Michael Mitch Apr 18 '21 at 11:37
  • Ok. But you can choose what to append to a `FormGroup` in general. The presence of a variable `controlName` in a component does not force you to put that element in a `FormGroup`. You do it manually and intentionally. – Francesco Lisandro Apr 18 '21 at 13:05
  • when i do not set the `controlName` i got an error......core.js:5973 ERROR NullInjectorError: R3InjectorError(MenuModule)[FormGroupDirective -> FormGroupDirective -> FormGroupDirective -> FormGroupDirective]: NullInjectorError: No provider for FormGroupDirective! – Michael Mitch Apr 18 '21 at 18:59
  • Please take a look at this https://stackoverflow.com/questions/53588169/how-to-use-formgroupname-inside-child-components/53588596 – Francesco Lisandro Apr 18 '21 at 19:37
  • this doen't help. I can use the component with a FormControl.. But i want to use it also in a component where i do not have a formgroup.. – Michael Mitch Apr 19 '21 at 13:42

0 Answers0