我正在使用带反应形式的 Angular 6,我需要在可编辑和自定义'readonly'视图之间切换形式。项目中有多个自定义输入组件,因此似乎最简单的方法是在 custom-form 元素上使用[1]绑定。问题是:
如何在 custom-input 组件中获取父级的 readOnly 值而不直接绑定到每个组件?
例如:
表格模板
<custom-form formGroup="formGroup" [readOnly]="!(canEdit$ | async)">
<custom-input formControlName="field1"></custom-input>
<custom-input formControlName="field2"></custom-input>
<custom-select formControlName="field3"></custom-select>
...
</custom-form>
自定义输入模板
// Show input if form readOnly is false
<input *ngIf="!formIsReadOnly"...>
// Show some other representation if not
<span *ngIf="formIsReadOnly">...</span>
1 回答
如果您不想将
readonly
输入参数添加到自定义控件,那么您将需要一个服务或一个不透明的标记,每个控件都从其构造函数中获取,以确定该控件是否只读。对于不透明的令牌,您需要在应用程序的根目录中提供一个布尔值,然后在您想要更改它时,您必须 re-provide。
服务(演示)
如果您希望能够在关闭时切换只读值,则需要使用服务。
readonly.service.ts
readonly.component.ts
customInput.component.ts
customInput.component.html