Angular FormBuilder未在选择框上呈现初始值

Angular FormBuilder未在选择框上呈现初始值,angular,angular-material,Angular,Angular Material,我创建了用于编辑地址的对话框组件。我使用'address'变量将详细信息传递给对话框组件。对话框组件一出现,我就在输入字段中获得初始值,而不是在选择框中。请参阅下面我的代码: .ts export class EditaddressDialogComponent implements OnInit { personId: any; editAddressForm: FormGroup; barangays: any[] = []; municipals: any[] = [];

我创建了用于编辑地址的对话框组件。我使用'address'变量将详细信息传递给对话框组件。对话框组件一出现,我就在输入字段中获得初始值,而不是在选择框中。请参阅下面我的代码:

.ts

export class EditaddressDialogComponent implements OnInit {
  personId: any;
  editAddressForm: FormGroup;
  barangays: any[] = [];
  municipals: any[] = [];
  provinces: any[] = [];
  regions: any[] = [];

  addressToEdit: any;

  addressTypes: any = [
    {value: 'Home Address', name: 'Home Address'},
    {value: 'Permanent Address', name: 'Permanent Address'},
    {value: 'Billing Address', name: 'Billing Address'}
  ];

  constructor(
    public dialogRef: MatDialogRef<EditaddressDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any,
    private fb: FormBuilder,
    private addressService: AddressService
  ) { }

  ngOnInit() {
    this.getRegions();
    this.addressToEdit = this.data;
    this.editAddressForm = this.fb.group({
      addresstype: [this.data.address.AddressType, Validators.required],
      unitnumber: [this.data.address.UnitNumber],
      housenumber: [this.data.address.HouseNumber],
      streetname: [this.data.address.StreetName],
      villagesubdivision: [this.data.address.VillageSubdivision],
      barangaycode: [this.data.address.BarangayCode],
      municipalcode: [this.data.address.MunicipalCode],
      provincecode: [this.data.address.ProvinceCode],
      regioncode: [this.data.address.RegionCode],
    });
    console.log(this.addressToEdit.address.RegionCode);

  }

  getRegions() {
    this.addressService.getRegions().subscribe((data: any) => {this.regions = data; });
  }

  onRegionChange(event: MatOptionSelectionChange, region: any) {
    this.provinces = null;
    if (event.source.selected) {
      this.addressService.getProvinces(region)
        .subscribe((data: any) => {
          this.provinces = data;
        });
    }
  }

  onProvinceChange(event: MatOptionSelectionChange, province: any) {
    this.municipals = null;
    if (event.source.selected) {
      this.addressService.getMunicipals(province)
        .subscribe((data: any) => {
          this.municipals = data;
        });
    }
  }

  onMunicipalChange(event: MatOptionSelectionChange, municipal: any) {
    this.barangays = null;
    if (event.source.selected) {
      this.addressService.getBarangays(municipal)
        .subscribe((data: any) => {
          this.barangays = data;
        });
    }
  }

   // ============== getters ==================
   get addresstype() {
    return this.editAddressForm.get('addresstype');
  }
  addressTypeError() {
    return this.addresstype.hasError('required') ? 'This field is required' : '';
  }
  get unitnumber() {
    return this.editAddressForm.get('unitnumber');
  }
  get housenumber() {
    return this.editAddressForm.get('housenumber');
  }
  get streetname() {
    return this.editAddressForm.get('streetname');
  }
  get villagesubdivision() {
    return this.editAddressForm.get('villagesubdivision');
  }
  get barangaycode() {
    return this.editAddressForm.get('barangaycode');
  }
  get municipalcode() {
    return this.editAddressForm.get('municipalcode');
  }
  get provincecode() {
    return this.provincecode.get('provincecode');
  }
  get regioncode() {
    return this.editAddressForm.get('regioncode');
  }
}
导出类EditaddressDialogComponent实现OnInit{
人形:任何;
editAddressForm:FormGroup;
barangays:任何[]=[];
市政:任何[]=[];
省份:任何[]=[];
地区:任何[]=[];
地址编辑:任何;
addressTypes:any=[
{值:'家庭地址',名称:'家庭地址'},
{值:'永久地址',名称:'永久地址'},
{值:'账单地址',名称:'账单地址'}
];
建造师(
公共dialogRef:MatDialogRef,
@注入(MAT_DIALOG_DATA)公共数据:任意,
私人fb:FormBuilder,
专用地址服务:地址服务
) { }
恩戈尼尼特(){
这个.getRegions();
this.addressToEdit=this.data;
this.editAddressForm=this.fb.group({
addresstype:[this.data.address.addresstype,验证器。必需],
unitnumber:[此.data.address.unitnumber],
门牌号:[this.data.address.housenumber],
streetname:[this.data.address.streetname],
villagesubdivision:[this.data.address.villagesubdivision],
barangaycode:[this.data.address.barangaycode],
市政编码:[this.data.address.市政编码],
provincecode:[此.data.address.provincecode],
regioncode:[this.data.address.regioncode],
});
log(this.addressToEdit.address.RegionCode);
}
getRegions(){
this.addressService.getRegions().subscribe((数据:any)=>{this.regions=data;});
}
onRegionChange(事件:MatOptionSelectionChange,区域:任意){
this.provides=null;
if(event.source.selected){
this.addressService.getProvisions(region)
.订阅((数据:任意)=>{
此参数=数据;
});
}
}
onProvinceChange(事件:MatOptionSelectionChange,省:任意){
this.municipals=null;
if(event.source.selected){
this.addressService.getMunicipals(省)
.订阅((数据:任意)=>{
这是。市政=数据;
});
}
}
市政变更(事件:MatOptionSelectionChange,市政:任何){
this.barangays=null;
if(event.source.selected){
this.addressService.getBarangays(市政)
.订阅((数据:任意)=>{
这个.barangays=数据;
});
}
}
//=====================获取者==================
获取地址类型(){
返回此.editAddressForm.get('addresstype');
}
addressTypeError(){
返回此.addresstype.hasError('required')?“此字段是必需的”:“”;
}
获取unitnumber(){
返回此.editAddressForm.get('unitnumber');
}
获取门牌号(){
返回此.editAddressForm.get('housenumber');
}
获取streetname(){
返回此.editAddressForm.get('streetname');
}
get villagesubdivision(){
返回此.editAddressForm.get('villagesubdivision');
}
获取barangaycode(){
返回这个.editAddressForm.get('barangaycode');
}
获取市政代码(){
返回此.editAddressForm.get('市政代码');
}
获取provincecode(){
返回此.provincecode.get('provincecode');
}
获取regioncode(){
返回此.editAddressForm.get('regioncode');
}
}
.html

<form [formGroup]="editAddressForm">

        <div class="col-md-6">
          <div class="occupy-half">
            <mat-form-field>
              <mat-select placeholder="Address Type" formControlName="addresstype">
                <mat-option>--</mat-option>
                <mat-option *ngFor="let type of addressTypes" [value]="type.value">
                  {{type.name}}
                </mat-option>
              </mat-select>
              <mat-error *ngIf="addresstype.invalid">
                <mat-icon matSuffix>block</mat-icon> &nbsp; {{ addressTypeError() }}</mat-error>
            </mat-form-field>
            <mat-form-field>
              <mat-label>Unit Number</mat-label>
              <input type="text" matInput formControlName="unitnumber">
            </mat-form-field>
            <mat-form-field>
              <mat-label>House Number</mat-label>
              <input type="text" matInput formControlName="housenumber">
            </mat-form-field>
            <mat-form-field>
              <mat-label>Street Name</mat-label>
              <input type="text" matInput formControlName="streetname">
            </mat-form-field>
            <mat-form-field>
              <mat-label>Village / Subdivision</mat-label>
              <input type="text" matInput formControlName="villagesubdivision">
            </mat-form-field>
          </div>
        </div>

        <div class="col-md-6">
          <div class="occupy-half">
            <mat-form-field>
              <mat-select placeholder="Region" formControlName="regioncode">
                <mat-option>--</mat-option>
                <mat-option *ngFor="let region of regions" [value]="region.RegionCode" (onSelectionChange)="onRegionChange($event, region.RegionCode)">
                  {{region.Region}}
                </mat-option>
              </mat-select>
            </mat-form-field>
            <mat-form-field>
              <mat-select placeholder="Province" formControlName="provincecode">
                <mat-option>--</mat-option>
                <mat-option *ngFor="let province of provinces" [value]="province.ProvinceCode" (onSelectionChange)="onProvinceChange($event, province.ProvinceCode)">
                  {{province.ProvinceName}}
                </mat-option>
              </mat-select>
            </mat-form-field>
            <mat-form-field>
              <mat-select placeholder="Municipal" formControlName="municipalcode">
                <mat-option>--</mat-option>
                <mat-option *ngFor="let municipal of municipals" [value]="municipal.MunicipalCode" (onSelectionChange)="onMunicipalChange($event, municipal.MunicipalCode)">
                  {{municipal.MunicipalName}}
                </mat-option>
              </mat-select>
            </mat-form-field>
            <mat-form-field>
              <mat-select placeholder="Barangay" formControlName="barangaycode">
                <mat-option>--</mat-option>
                <mat-option *ngFor="let barangay of barangays" [value]="barangay.BarangayCode">
                  {{barangay.BarangayName}}
                </mat-option>
              </mat-select>
            </mat-form-field>
            <button mat-raised-button color="accent" style="display: block; width: 100%;" (click)="onSubmit()">Submit</button>
          </div>
        </div>
      </form>

--
{{type.name}
块{{addressTypeError()}}
单元号
门牌号
街道名称
乡村/分区
--
{{region.region}
--
{{province.ProvinceName}
--
{{市政府名称}
--
{{barangay.BarangayName}
提交

当我在OnInit期间使用控制台日志时,我会得到输入框和选择框中应该使用的值。事实上,就像我说的,我把它放在输入框里。但是在选择框中,我没有得到任何。但是,当我更改“区域”框时,会触发onchange事件。你能帮个忙吗?谢谢。

我会在您的
选择垫中使用
比较功能。此方法(在ts文件中定义)将用于比较

HTML示例:

<mat-select placeholder="Address Type" formControlName="addresstype" [compareWith]="compareById">
   <mat-option *ngFor="let type of addressTypes" [value]="type"> {{ type.name }} </md-option>
</mat-select>

然后
addresstype
的formcontroll将需要采用
addresstype
对象,而不仅仅是值。

必须尝试在构造函数中构造表单生成器,然后在ngOnInit中显式设置值?或者在以后的钩子中,比如afterviewinit。你能给我一个例子吗?在我的构造函数中,我可以这样做。。。this.editAddressForm=this.fb.group({addresstype:[null,Validators.required],…。如何在查看后设置值?实现ngAfterViewInit(){this.editAddressForm.controls['barangaycode'].setValue('new value here')}可能之后,添加这个.editAddressForm.updateValueAndValidity()
addressTypes: any = [
    {id: 1, value: 'Home Address', name: 'Home Address'},
    {id: 2, value: 'Permanent Address', name: 'Permanent Address'},
    {id: 3, value: 'Billing Address', name: 'Billing Address'}
  ];

compareById(obj1, obj2) {
   return obj1.id === obj2.id;
}