【问题标题】:Implementing a standard layout for reusable components in Angular在 Angular 中为可重用组件实现标准布局
【发布时间】:2023-01-29 20:57:33
【问题描述】:

我正在构建可重用的 UI 控件,这些控件遵循 FormLayoutComponent 中指定的特定布局和功能(标签、编辑/确认按钮、读/写视图等)。

我目前必须在每个 UI 组件中指定 FormLayoutComponent 的输入/输出。

如果我需要向 FormLayoutComponent 添加新的输入/输出,我将不得不遍历每个 UI 组件并更新它们。

我可以让 FormLayoutComponent 和 UI 组件扩展一个抽象类。这会处理打字稿类,但如果添加新属性,html 模板仍需要更新。

export abstract class AbstractLayout<T = any> {
  @Input() control: FormControl<T | null> = new FormControl<T | null>(null);
  @Output() confirm: EventEmitter<T | null> = new EventEmitter<T | null>();
  @Input() defaultMode: DefaultMode = 'read';
  @Input() showEditButton = true;
  @Input() editButtonIcon = 'edit';
  @Input() showConfirmButton = true;
  @Input() showCancelButton = true;
  @Input() showLabel = true;
  @Input() requireConfirmation = true;
  @Input() label: string = '';
}

在 Angular 中是否有更好的方法来实现这一点,或者当新的输入/输出添加到 FormLayoutComponent 时我是否必须更新每个 UI 组件?

Stackblitz 示例:https://stackblitz.com/edit/angular-layout-composition

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    我也有兴趣听听这里人群的智慧,但根据我在自定义表单字段方面的经验,我发现重复的 HTML 比拥有一个包含所有可能表单字段类型的条件逻辑的组件/HTML 文件要简单得多,尤其是随着这些组件的增长以处理新的奇怪和奇妙的需求。

    不幸的是,我们没有办法在 Angular 中提取可重用的“模板片段”;建议只为任何需要模板的东西创建组件,这在实践中不会扩展到用例,例如“相似但不同”的表单字段库。

    正如您所提到的,我目前正在使用一系列基类来抽象出通用逻辑。例如

    class ValueAccessorBase { // ... }
    class FormElementBaseDirective extends ValueAccessorBase { // ... }
    class BaseInputDirective extends FormElementBaseDirective { // ... }
    class FormInputTextComponent extends BaseInputDirective { // ... }
    

    注意:我正在滥用 @Directive 装饰器以允许这些基类接受 @Input() 属性,然后与扩展它们的所有组件共享这些属性。实际上,这些都只是美化的class(最后一个组件除外)

    这是迄今为止我找到的最佳解决方案,但存在所有典型的继承问题(如果您有简单的组件需求,您可能永远不会遇到)。由于@Inputs/@Directives 的挑战启发了this question,我还没有找到重构组合的方法

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-06
      • 1970-01-01
      • 2019-04-01
      • 2017-01-07
      • 2012-07-03
      • 1970-01-01
      • 2011-01-18
      相关资源
      最近更新 更多