【问题标题】:How to enable the input and button from parent component in angular?如何以角度启用父组件的输入和按钮?
【发布时间】:2019-06-04 08:25:55
【问题描述】:

我有以下父组件,

app.component.html:

<h1> Look at console </h1>
<app-profile-image></app-profile-image>

app.component.ts:

  ngOnInit() {

    console.log((document.getElementById('fileInput') as any));

    console.log((document.getElementById('fileInput') as any).disabled);

    console.log((document.getElementsByClassName('hover-text') as any));

    console.log((document.getElementsByClassName('hover-text') as any)[0].disabled)
  }

您可以在示例https://stackblitz.com/edit/angular-file-upload-preview-zaipvg

中看到父子组件的实现

在子组件中,您可以看到以下内容,

  <button class="hover-text" [disabled]="true">Choose file</button>

<input id="fileInput" type='file' (change)="onSelectFile($event)" [disabled]="true">

默认情况下两者都处于禁用状态..

我想要做的是需要使用 parent 启用这两个禁用的属性

我正在使用的子 &lt;app-profile-image&gt;&lt;/app-profile-image&gt; 是我真实应用程序中的库,这意味着我不能直接更改子代码,因此我需要通过父代码更改 disabled 属性才能启用..

我试过了,

console.log((document.getElementById('fileInput') as any));

console.log((document.getElementsByClassName('hover-text') as any));

两者都提供禁用属性(您可以在给定示例中看到控制台)

但是,

console.log((document.getElementById('fileInput') as any).disabled);

console.log((document.getElementsByClassName('hover-text') as any)[0].disabled)

给出的结果为 false,但我在上面给出的 console.log 中得到了 disabled 属性,但是为什么即使该属性存在,我也会得到 false 作为结果?

如果它给出的结果为true,则已知禁用为真,因此根据条件我可以启用按钮和输入,但不知道它在控制台中将禁用为假的原因..

请帮助我使用only parent component(即app.component.ts)在given example 中启用禁用的buttoninput,以便我可以选择要上传的任何图像在里面..

我无法编辑子组件,因为它是一个库包,我的实际应用程序中没有任何代码,我唯一能做的就是我可以单独编辑父组件..

【问题讨论】:

  • 创建全局变量并从@Output 获取数据,然后分配给变量。变量值是真假。将它们替换为[disabled]="variable"
  • @Florian,你做了什么编辑?我只能看到结果而不是您更改的代码..即使输出本身就像我给出的一样..
  • @Abhishek,我无法编辑子项中的任何内容,因为它是另一个库,我已通过 npm install fileupload.. 安装。
  • @HelloWorld 我没有改变孩子,但我不明白你需要启用按钮。我目前正在寻找解决方案

标签: javascript html angular typescript input


【解决方案1】:

在你的 app.component.html 中:

<app-profile-image (mouseenter)=onProfileImageHovered()></app-profile-image>

在你的 app.component.ts 中:

onProfileImageHovered(){
  document.getElementById('fileInput')['disabled'] = false;
  const hoverTextCollection = document.getElementsByClassName('hover-text');
  if (!hoverTextCollection) {
    return null;
  }
  const btn = Array.from(hoverTextCollection).find((e) => {
    return (e instanceof HTMLButtonElement &&
            e.innerHTML === 'Choose file');
  });
  if(btn) {
    btn['disabled'] = false;
  }
}

stackblitz

【讨论】:

  • 这是一种好的方法吗?如果我在子组件中有 5 或 6 个按钮标签,无论如何会发生什么?
【解决方案2】:

您好,您可以在子组件中使用 Input 属性。 这是工作示例https://stackblitz.com/edit/angular-file-upload-preview-ptgq2f 如果答案对您有用,请接受。

【讨论】:

  • 我已经明确提到我无法更改子组件。
  • 对不起,我错过了。你能重新检查我的答案吗
猜你喜欢
  • 1970-01-01
  • 2018-11-24
  • 1970-01-01
  • 1970-01-01
  • 2020-07-23
  • 2021-01-26
  • 2022-11-24
  • 1970-01-01
  • 2019-10-18
相关资源
最近更新 更多