我们有一个基于模板的表单,它使用各种角度材质控件(matInput、mat-select等)。我们想为一些用户创建一个“只读”类型的视图。我立即想到的是简单地检查用户的特权,然后遍历所有表单控件,并在需要时将其设置为禁用。
这似乎适用于文本输入类型控件,但不适用于选择和复选框。另外,这会使控件变灰,这不一定是我们想要的。
有没有关于如何最好地完成这一点的想法?也许在表单中禁用键盘和鼠标输入可能是我们想要的,但我不知道该怎么做。
发布于 2017-11-02 15:34:29
我认为这是可能的,但你必须检查所有的控件类型,例如MatInput公开readonly属性,它允许我们创建简单的指令来切换整个表单的readonly状态:
import {Directive, ContentChildren, QueryList, AfterContentInit, Input} from '@angular/core';
import {NgModel} from '@angular/forms';
@Directive({
selector: 'form[readonly]'
})
export class FormReadonlyDirective implements AfterContentInit
{
@ContentChildren(NgModel)
public inputs:QueryList<NgModel>;
private controls:any[];
private _readonly:boolean = false;
public ngAfterContentInit():void
{
this.controls = this.getControls();
this.inputs.changes.subscribe(() =>
{
this.setReadonly(this.readonly);
});
this.setReadonly(this.readonly);
}
@Input()
public get readonly():boolean
{
return this._readonly;
}
public set readonly(value:boolean)
{
this._readonly = value != null && value !== false && `${value}` !== 'false';
this.setReadonly(value);
}
private setReadonly(value:boolean):void
{
if(this.controls != null)
{
this.controls.forEach(control =>
{
//todo: check
control.readonly = value;
});
}
}
private getControls():any[]
{
return this.inputs.map(control => control.valueAccessor);
}
}没有经过测试,但您已经明白了。
https://stackoverflow.com/questions/47063295
复制相似问题