【问题标题】:Accessing HTML field of Parent Component in Library's component访问库组件中父组件的 HTML 字段
【发布时间】:2018-08-30 22:33:04
【问题描述】:

我使用“ng generate library”命令创建了一个 Angular 6 库。该库在 --prod build 之后在我的基础组件中使用,然后在主应用程序的 app.module.ts 中导入。库中的...组件文件有@Input("leftPanel") leftPanel: ElementRef;

base.component.html 上的 HTML Div 元素是这样的:<div #leftPanel></div> 以及使用其选择器的库元素:
<lib-ng-mylibrary [leftPanel]="leftPanel"> </lib-ng-mylibrary>

库组件实现 AfterViewInit。在实现方法中,这段代码执行失败:this.leftPanel.nativeElement.style.flexBasis = '50%'; 它说, this.leftPanel.nativeElement 是未定义的。但我可以看到 this.leftPanel 指向 div。想知道为什么即使 @Input leftPanel 是“ElementRef”类型,它也不允许 this.leftPanel.nativeElement`?

提前致谢!

【问题讨论】:

    标签: angular6 angular-library


    【解决方案1】:

    哈沙德

    而不是发送父ElementRef 我的感觉是你的组件应该有和@Output 并触发由父处理的事件,以更改本机面板宽度。

    这样做可以减少对象之间的耦合并使它们更可重用。

    在此处查看文档:https://angular.io/guide/component-interaction

    还是想用 ElementRef 作为参数

    如果您仍想将 leftPanel 作为参数发送,您还需要在主组件中添加一个 @Input() 变量,这样它就可以将 <div #leftPanel> 解析为局部变量,并且该变量可以在 @987654325 中使用@

    干杯

    【讨论】:

    • 谢谢汉密尔顿。我喜欢发射事件的想法。我会试试的。我将输入变量类型从 ElementRef 更改为字符串,并从应用程序 base.component.html 更改为以 html 元素的 ID 而不是 ref 发送。然后在库中,使用 getElementById 访问父组件的 html 字段。它有效,但我更喜欢建议的松散耦合方式。
    猜你喜欢
    • 2019-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 2018-01-26
    • 1970-01-01
    相关资源
    最近更新 更多