按照DYNAMIC FORMS上的文档,我可以正确运行示例。现在我想添加一个自定义选择:ng2-select。
该组件是下一个(来自文档):
import { Component, Input, ViewEncapsulation } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { QuestionBase } from '../question/question-base';
@Component({
selector: 'df-question',
encapsulation: ViewEncapsulation.None,
templateUrl: 'dynamic-form-question.component.html'
})
export class DynamicFormQuestionComponent {
@Input() question: QuestionBase<any>;
@Input() form: FormGroup;
get isValid() { return this.form.controls[this.question.key].valid; }
}
html
:_
<div [formGroup]="form">
<label [attr.for]="question.key">{{question.label}}</label>
<div [ngSwitch]="question.controlType">
<input *ngSwitchCase="'textbox'" class="form-control" [formControlName]="question.key"
[id]="question.key" [type]="question.type">
<div *ngSwitchCase="'dropdown'">
<ng-select [allowClear]="true"
[items]="question.options"
(data)="question.refreshValue($event)"
(selected)="question.selected($event)"
</ng-select>
</div>
</div>
<div class="errorMessage" *ngIf="!isValid">{{question.label}} is required</div>
</div>
而且question-dropdown.ts
是:
import { QuestionBase } from './question-base';
export class DropdownQuestion extends QuestionBase<string> {
controlType = 'dropdown';
options: {id: string, text: string}[] = [];
constructor(options: {} = {}) {
super(options);
this.options = options['options'] || [];
}
public selected(value: any): void {
console.log('Selected value is: ', value);
}
public refreshValue(value: any): void {
this.value = value;
}
}
所以,它几乎可以工作了。问题是我看不到sex
选择的值。输出如下:
保存了以下值 {"name":"foo","emailAddress":"foo@gmail.com","sex":""}
是的,我稍微改了一下question.service.ts
,给需要的人,这里是:
import { Injectable } from '@angular/core';
import { DropdownQuestion } from './question-dropdown';
import { QuestionBase } from './question-base';
import { TextboxQuestion } from './question-textbox';
@Injectable()
export class QuestionService {
// Todo: get from a remote source of question metadata
// Todo: make asynchronous
getQuestions() {
let questions: QuestionBase<any>[] = [
new DropdownQuestion({
key: 'sex',
label: 'Sex',
options: [
{id: 'male', text: 'Male'},
{id: 'female', text: 'Female'}
],
order: 3
}),
new TextboxQuestion({
key: 'name',
label: 'First and Last Name',
value: '',
required: true,
order: 1
}),
new TextboxQuestion({
key: 'emailAddress',
label: 'Email',
type: 'email',
order: 2
})
];
return questions.sort((a, b) => a.order - b.order);
}
}
如何将 与 相关联ng2-select
以formgroup
获得正确的输出?