我只能从表单中获取它们的值

时间:2019-11-26 12:41:41

标签: angular typescript

我有这个表格:

<div class="form-group modal-body">
    <form [formGroup]="mediadorForm" #form>
      <input type="hidden" name="angcod" id="angcod" formControlName="angcod" class="form-control" [(value)]="mediador.angcod" #angcod>
      <input type="text" name="angnom" id="angnom" formControlName="angnom" class="form-control" placeholder="Nombre del mediador" [(value)]="mediador.angnom" #angnom required>
      <div class="row mt-3">
        <div class="col-5 pt-1">Factura comisiones</div>
        <div class="col-7">
          <select class="form-control" name="angfac" id="angfac" formControlName="angfac" #angfac>
            <option [(value)]="sn.desres" *ngFor="let sn of sino" [selected]="sn.desres === mediador.angfac">{{ sn.desnom }}</option>
          </select>
        </div>
      </div>
    </form>
  </div>

  <div class="modal-footer">
    <button type="button" class="btn btn-success" (click)="enviaForm(mediadorForm); editMediadorModal.close();">- Guardar cambios -</button>
    <button type="button" class="btn btn-secondary" data-dismiss="modal" (click)="editMediadorModal.close();">Cancelar</button>
  </div>

然后在组件上显示:

export class MediadorComponent implements DoCheck, OnInit {

  mediadorForm: FormGroup;
  mediador: Mediador;

  constructor(private fb: FormBuilder) {

  }

  ngOnInit() {
    this.mediadorForm = this.fb.group({
      angcod: '',
      angnom: '',
      angfac: ''
    });
  }

  ngDoCheck() {
    this.mediador = this.mediadorService.mediador;
  }

  enviaForm(form: any) {
    console.log(form.value);
  }
}

该表单将其值加载到字段中,但是如果我发送它,则控制台日志输出

Object { angcod: "", angnom: "", angfac: "" }

如果我什么都没改变。如果我将angnom的值从“ John Doe”更改为“ Barak Obama”,则会输出:

Object { angcod: "", angnom: "Barak Obama", angfac: "" }

但未更改的值为空。

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

将值分配给表单的最佳方法是

    this.mediadorForm = this.fb.group({ angcod: 'mediador.angcod', 
angnom: 'mediador.angnom', 
angfac: 'mediador.angfac' });