Viewchild return 未定义
Viewchild return undefined
我想使用 html 锚点和 child 组件。我正在尝试使用 @ViewChild
但值 return 未定义。你能帮帮我吗?
我的标题组件:
//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>
兄弟组件之间通信的解决方案:
只能在同一个组件的ts文件中调用@ViewChild,
而不是在不同的组件中。
因此,在 HomeComponent 模板中,我们在 <app-anchor>
中放置一个 id (#anchor
),
然后我们将它绑定到 HeaderComponent @Input 成员。
现在您可以访问 HeaderComponent 中的所有 AnchorComponent 成员了。
解-
主页组件
<app-header [anchorComponent]="anchor"></app-header>
<app-anchor #anchor></app-anchor>
HeaderComponent:
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;
我想使用 html 锚点和 child 组件。我正在尝试使用 @ViewChild
但值 return 未定义。你能帮帮我吗?
我的标题组件:
//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>
兄弟组件之间通信的解决方案:
只能在同一个组件的ts文件中调用@ViewChild, 而不是在不同的组件中。
因此,在 HomeComponent 模板中,我们在 <app-anchor>
中放置一个 id (#anchor
),
然后我们将它绑定到 HeaderComponent @Input 成员。
现在您可以访问 HeaderComponent 中的所有 AnchorComponent 成员了。
解-
主页组件
<app-header [anchorComponent]="anchor"></app-header>
<app-anchor #anchor></app-anchor>
HeaderComponent:
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;