Angular 2自定义控件内部表单,默认值为[object Object]

时间:2018-03-12 16:11:30

标签: javascript html angular typescript

我有一个简单的angular2反应形式:

formangular.component.html

<form novalidate (ngSubmit)="onSubmit(formDir.value)" [formGroup]="complexForm" #formDir="ngForm">
  <div class="form-group">
    <custom-input id="idCausaleRitenuta"
                  class="form-control"
                  label="Codice:"
                  formControlName="idCausaleRitenuta"
                  [(ngModel)]="idCausaleRitenuta"></custom-input>
    <div *ngIf="idCausaleRitenuta.invalid && (idCausaleRitenuta.dirty || idCausaleRitenuta.touched)"
         class="alert alert-danger">
........

相对的.ts文件:

formangular.component.ts

export class FormAngularComponent { 
get idCausaleRitenuta() { return this.complexForm.get('idCausaleRitenuta');}

constructor(private fb: FormBuilder, private ritenuteService: RitenuteService, private sharedService: SharedService) {
this.createForm();}

createForm() {
this.complexForm = this.fb.group({
  idCausaleRitenuta: ['', Validators.compose([Validators.required, Validators.maxLength(4)])],
........

...和自定义输入控件:

custominput.component.ts

.................

@Component({
  selector: 'custom-input',
  template: `<div>
              <label *ngIf="label" [attr.for]="identifier">{{label}}</label>
               <input [id]="identifier"
                      [type]="type"
                      [class]="class"
                      [placeholder]="placeholder"
                      [(ngModel)]="value"
                      (blur)="touch()" />
            </div>`,
.......
})

export class CustomInputComponent<T> implements ControlValueAccessor {
.........

  identifier = `custom-input-${identifier++}`;

  private innerValue: T;

  private changed = new Array<(value: T) => void>();
  private touched = new Array<() => void>();

  get value(): T {
    return this.innerValue;
  }
  set value(value: T) {
    if (this.innerValue !== value) {
      this.innerValue = value;
      this.changed.forEach(f => f(value));
    }
  }
  touch() {
    this.touched.forEach(f => f());
  }
  writeValue(value: T) {
    this.innerValue = value;
  }
  registerOnChange(fn: (value: T) => void) {
    this.changed.push(fn);
  }
  registerOnTouched(fn: () => void) {
    this.touched.push(fn);
  }
}

let identifier = 0;

当我渲染表单时,'自定义控件'中输入的值是'[object Object]',有人可以告诉我为什么吗?

1 个答案:

答案 0 :(得分:0)

当您拨打此电话时:

get idCausaleRitenuta() { return this.complexForm.get('idCausaleRitenuta');}

您实际上是获取FormControl对象(而不是表单控件的值)。

您可以像这样访问该控件的value属性:

get idCausaleRitenuta() { return this.complexForm.get('idCausaleRitenuta').value;}