我有一个动态表单(使用angular.io动态表单实例plunkr做了一个例子),我想禁用此表单的输入,将其显示为只读信息.
所以我决定在问题模型中添加disabled属性:
export class QuestionBase<T>{
value: T;
key: string;
label: string;
required: boolean;
order: number;
controlType: string;
disabled?:boolean;
constructor(options: {
value?: T,
key?: string,
label?: string,
required?: boolean,
order?: number,
controlType?: string,
disabled?:boolean
} = {}) {
this.value = options.value;
this.key = options.key || '';
this.label = options.label || '';
this.required = !!options.required;
this.order = options.order === undefined ? 1 : options.order;
this.controlType = options.controlType || '';
this.disabled = options.disabled || false;
}
}
然后我将disabled绑定到输入:
<input *ngSwitchCase="'textbox'" [disabled]="question.disabled" [formControlName]="question.key"
[id]="question.key" [type]="question.type">
我收到警告,输入未被禁用:
It looks like you're using the disabled attribute with a reactive form directive. If you set disabled to true
when you set up this control in your component class, the disabled attribute will actually be set in the DOM for
you. We recommend using this approach to avoid 'changed after checked' errors.
Example:
form = new FormGroup({
first: new FormControl({value: 'Nancy', disabled: true}, Validators.required),
last: new FormControl('Drew', Validators.required)
});
所以我确实喜欢它写在警告中我得到一个问题,验证器似乎不喜欢禁用字段,即使它没有标记为必需.
这是我更改了新的QuestionControlService类:
@Injectable()
export class QuestionControlService {
constructor() { }
toFormGroup(questions: QuestionBase<any>[] ) {
let group: any = {};
questions.forEach(question => {
group[question.key] = question.required ? new FormControl({value: question.value || '', disabled: question.disabled}, Validators.required)
: new FormControl({value: question.value || '', disabled: question.disabled});
});
return new FormGroup(group);
}
}
问题
禁用的测试字段已禁用,但无效,这是不可能的,因为它根本没有被修改.
Plunkr我的问题:http://plnkr.co/edit/qSDnD2xWWUwafyToDNX1?p=preview
最佳答案 我在
github提交了一个问题,结果发现这是理想的行为.
我的错误是检查每个字段的有效性,而不是检查整个表单.