子表单溢出了mat-form-field宽度

时间:2018-10-28 23:27:17

标签: angular material

我创建了一个用于处理北美电话号码的角度组件。它完全可以正常工作。不幸的是,当我将其包含在父级mat-form-field中时,子级会超出父级的宽度。我想让父级跟踪子级的宽度,因为并非所有字段都必须可见,这取决于应用程序的使用情况。 (例如电话类型选择,长途电话“ +1”和复选框和/或“ x” +分机号输入字段。)

我可以通过编程方式在应用程序中或使用CSS来设置mat-form-field的宽度,但是我无法从组件中获取正确的值来自动化它。

Test showing mat-form-field with aqua background

TypeScript:

 import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { UsPhoneNumber } from './_classes/us-phone-number';
import { UsPhoneNumberComponent } from './_components/us-phone-number/us-phone-number.component';
import { FormBuilder,
  FormGroup,
  FormControl,
 } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'Phone Test';
  myform : FormGroup;
  zerror = true;
  matPhoneNumber : UsPhoneNumber;

  types: string[] = ['Home','Work','Cell']

  ddd: string = '8005551212';
  eee: string = '40773377721000'
  abc='auto';
  constructor(    
    private formBuilder: FormBuilder // private fm: FocusMonitor,
) {
  this.myform = formBuilder.group(
    {
      myPhone : new FormControl(new UsPhoneNumber('4777337777')),
      matPhone : new FormControl(new UsPhoneNumber('18005551212'))
    })
  }
}

HTML:

<form [formGroup]='myform'>
    <app-us-phone-number formControlName='myPhone' [phoneTypes]='types' #ppp [value]="ddd" (phoneEvent)="onChange($event)"></app-us-phone-number>
    <br/>
    <mat-form-field appearance='outline' [ngStyle]="{'width':abc}">
        <mat-label>Phone Number</mat-label>
        <mat-hint>Area Code optional</mat-hint>
        <app-us-phone-number formControlName='matPhone' [phoneTypes]='types' #mmm [value]="eee" (phoneEvent)="onMatChange($event)"></app-us-phone-number>
        <mat-error *ngIf="mmm.errorState">{{matPhoneNumber.errmsg}}</mat-error>
    </mat-form-field>
</form>

1 个答案:

答案 0 :(得分:0)

我认为这应该是您想要的。将其放在您的styles.css中。

.mat-form-field-infix {
  width: auto !important;
}

实时示例:https://angular-material-form-field-wrapping-content.stackblitz.io