简体   繁体   English

窗体中的Angular 2自定义控件,默认值为[object Object]

[英]Angular 2 custom control inside form, default value is [object Object]

I've a simple angular2 reactive form: 我有一个简单的angular2反应形式:

formangular.component.html 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"> ........ 

the relative .ts file: 相对的.ts文件:

formangular.component.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)])], ........ 

...And the custom-input control: ...以及自定义输入控件:

custominput.component.ts 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; 

When I render the form, the value of the input inside the 'custom control' is '[object Object]', can someone tell me why? 渲染表单时,“自定义控件”内的输入值是“ [对象对象]”,有人可以告诉我原因吗?

When you make this call: 拨打电话时:

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

You are actually getting the FormControl object (not the value of the form control). 您实际上是在获取FormControl对象(而不是表单控件的值)。

You can access the value property of that control like this: 您可以像这样访问该控件的value属性:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM