[英]How to enable the input and button from parent component in angular?
我有以下内容的父级组件,
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启用这两个禁用的属性 。
我正在使用的子<app-profile-image></app-profile-image>
是我的真实应用程序中的库,这意味着我无法直接更改子代的代码,因此通过父代,我需要更改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中获取了disable属性,但是即使该属性存在,我为什么也得到false作为结果?
如果它给出的结果为true
则表示disabled为true,因此基于条件我可以启用按钮和输入,但不知道在控制台中将disabled设为false的原因。
请帮助我在给定示例中仅使用父组件 (即app.component.ts
)启用禁用的button
和input
,以便我可以选择要在其中上载的任何图像。
我无法编辑子组件,因为它是一个库程序包,并且我的实际应用程序中没有任何代码,而我唯一能做的就是我可以单独编辑父组件。
在您的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;
}
}
嗨,您可以在子组件中使用Input属性。 这是工作示例https://stackblitz.com/edit/angular-file-upload-preview-ptgq2f如果答案适合您,请接受。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.