首页 > 解决方案 > 在组件中绑定 formControlName | 可选用法

问题描述

如何将formControlName子组件中的 a 设置为可选?我想在没有 FormGroup 的 ComponentB 中使用 ComponentA,但也想在其他带有 Formgroup 的组件中使用 ComponentA。有没有可能?

组分A

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

组件A_TS

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

组分B

<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>

标签: angularangular-reactive-forms

解决方案


推荐阅读