Home > OS >  How to get a Value For FormField with suffix value
How to get a Value For FormField with suffix value

Time:11-15

I'm using angular material formfield with suffix dropdowns with units like cm,mm,etc..,In that I need a value of given number as input and suffix selected dropdowns value in one formcontrolName ,Here its my code.

<mat-form-field >
    <mat-label>Width</mat-label>
        <input matInput [formControlName]="'width'" type="number" autocomplete="off">
        <mat-select matSuffix >
           <ng-container *ngFor="let unit of unitArray" >
               <mat-option [value]="unit" >{{unit}}</mat-option>
           </ng-container>
         </mat-select>
</mat-form-field>


unitArray = ['pt','cm','mm','in','pi']

CodePudding user response:

It is not possible to combine both inputs in a single formControl. The reason is that the binding needs one single source of truth, e.g. for validation. You can just define a separate FormControl for your unit selection like:

form = new FormGroup({
  width: new FormControl(),
  unit: new FormControl()
});

and then bind your select to the new formControl:

<mat-select matSuffix formControlName="unit" >
  <ng-container *ngFor="let unit of unitArray" >
    <mat-option [value]="unit" >{{unit}}</mat-option>
  </ng-container>
</mat-select>

Then you can combine these two values on submit:

submit() {
  const value = `${this.form.value.width}${this.form.value.unit}`
  // use this value for whatever you want
}

CodePudding user response:

I try using 3 different controls widthNum, unit and totalWidth. In your.component.ts:

  exampleForm: FormGroup = this.fb.group({
    widthNum: [''],
    unit: [''],
    widthWhitUnit: [''],
  });

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.exampleForm.get('widthNum').valueChanges.subscribe(() => {
      this.exampleForm
        .get('widthWhitUnit')
        .setValue(
          this.exampleForm.get('widthNum').value  
            ' '  
            this.exampleForm.get('unit').value
        );
    });

    this.exampleForm.get('unit').valueChanges.subscribe(() => {
      this.exampleForm
        .get('widthWhitUnit')
        .setValue(
          this.exampleForm.get('widthNum').value  
            ' '  
            this.exampleForm.get('unit').value
        );
    });
  }
}

And an example for your.component.html:

<div [formGroup]="exampleForm">
  <input formControlName="widthNum" placeholder="width" />
  <input formControlName="unit" placeholder="unit" />
</div>

<div>
  <p>{{ this.exampleForm.get('widthWhitUnit')?.value }}</p>
</div>

I provide you some code on stackblitz at https://stackblitz.com/edit/angular-ivy-1gdwp3

  • Related