【问题标题】:Viewchild return undefinedViewchild 返回未定义
【发布时间】:2019-10-03 09:43:30
【问题描述】:

我想使用带有子组件的 html 锚。我正在尝试使用@ViewChild,但值返回未定义。你能帮帮我吗?

我的头组件:

//My html
<button (click)="scrollToElement(target)"></button>

//My TS
@ViewChild('target', { read: ViewContainerRef }) target;

scrollToElement($element): void {
  console.log($element);
  $element.scrollIntoView({behavior: "smooth", block: "start", inline: "nearest"});
}

我的homeComponent(用来集中所有组件)

<app-header></app-header>
<app-anchor></app-anchor>

我的锚组件:

<div #target>My target</div>

【问题讨论】:

  • 您是否尝试访问 AnchorComponent 中的 div 元素?你想要它在 HeaderComponent 中吗?
  • 是的,我的主菜单在 headerComponent 中,我想到达 AnchorComponent 中的 div

标签: angular anchor


【解决方案1】:

兄弟组件之间通信的解决方案:

@ViewChild 只能在同一组件的 TS 文件中调用, 而不是在不同的组件中。

所以,在 HomeComponent 模板中,我们在 &lt;app-anchor&gt; 中放置了一个 id (#anchor), 然后我们将它绑定到 HeaderComponent @Input 成员。

现在您可以访问 HeaderComponent 中的所有 AnchorComponent 成员。

解决方案 -

主页组件

<app-header [anchorComponent]="anchor"></app-header>
<app-anchor #anchor></app-anchor>

标头组件

TS:

@input() anchorComponent:AnchorComponent ;

scrollToElement(): void {
  //This is how to reach to your div#target
  console.log(this.anchorComponent.target);
  ...
}

AnchorComponent

HTML:

<div #target>My target</div>

TS:

@ViewChild('target', { read: ViewContainerRef }) target;

【讨论】:

    猜你喜欢
    • 2017-03-11
    • 2023-03-21
    • 2018-05-14
    • 2018-10-25
    • 2019-10-19
    • 2017-01-08
    • 2019-07-28
    • 2020-03-25
    • 2016-04-29
    相关资源
    最近更新 更多