【问题标题】:Angular Disable Container角度禁用容器
【发布时间】:2021-11-20 14:20:08
【问题描述】:

好的,所以我的问题是一个常见问题,但到目前为止我发现的答案并不令人满意和/或不能完全回答我的情况。

我创建了一种 c# 类型的 stackpanel 组件,它根据您选择的内容垂直或水平放置其内容。这个的html是:

<div #root
     [fxLayout]="this._orientation"
     fxLayoutAlign="flex-start"
     [fxLayoutGap]="this.spacing"
     [style.marginBottom]="this.margin_bottom"
     [style.marginLeft]="this.margin_left"
     [style.marginRight]="this.margin_right"
     [style.marginTop]="this.margin_top"
     [style.width]="this.width"
     [style.height]="this.height"
     [style.background]="this.background">
  <ng-content></ng-content>
</div>

fxLayout、fxLayoutAlign 和 fxLayoutGap 来自 angular flex 库,可以通过 npm 安装。

所以我想做的是有另一个变量

@Input() disabled: boolean;

在我的组件文件中,我想要做的是禁用 ng-content 中的所有子项。现在让我解释一下我不想要什么。我不希望在 div 上进行简单的样式更改以关闭点击事件,因为内容仍然可以通过选项卡切换,您甚至可以按键盘上的 enter 按钮来按下应该被禁用的按钮或控件。

所以我的想法是让所有的孩子都进入#root(div)并设置“禁用”属性。

private disableChildren(value: boolean) {
  const dom = this.root?.nativeElement?.children;
  if (dom == null) return;
  const list: Element[] = [].slice.call(dom);
  list.filter(x => x['disabled'] != null).forEach(x => x['disabled'] = value);
}

问题在于 this.root?.nativeElement?.children 是 HTMLElement 并且没有对组件文件的引用。此外,一些 html 子级具有禁用标记,而有些则没有。例如,“按钮”有一个禁用的标签,但“垫子图标”没有。我创建了一堆自定义组件,并在所有组件文件(如 mat-icon)中放置了一个“禁用”@Input,我想从父类设置该变量,但我没有看到尽可能。

所以要问的所有信息:

有没有办法在 ng-content 内的子组件上设置属性?就像从禁用子函数中的堆栈面板组件设置@Input 禁用属性一样?

有没有更好的方法来做到这一点?老实说,我不认为有,因为我已经寻找了几天来禁用 div 中的所有子项,但没有任何方法可以正常工作。

【问题讨论】:

    标签: html angular typescript


    【解决方案1】:
    ngAfterViewInit(): void {
      this.disableHTMLElement(this.container.nativeElement);
    }
    
    private disableHTMLElement(element: HTMLElement): void {
      element.setAttribute('disabled', this.disabled ? 'true' : 'false');
    
      const children: HTMLElement[] = Array.prototype.slice.call(element.children);
      children.forEach((child) => this.disableHTMLElement(child));
    }
    

    Stackblitz demo here

    【讨论】:

    • 不幸的是,这不会禁用带有自己的 html 的自定义组件。例如,我禁用的 stackpanel 组件中有另一个自定义组件:该组件仍然可以与之交互。
    • This stackblitz提供了一个自定义组件的例子,里面的输入是禁用的。
    • @PhilipVaughn 你能提供一个它不起作用的例子吗?
    猜你喜欢
    • 2019-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-22
    • 2023-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多