繁体   English   中英

Angular 10 scrollTo从父组件到子组件html中的元素

[英]Angular 10 scrollTo from parent component to an element in child component html

父 html:

 <div>
  <button type="button" (click)="scroll(childelementTwo)">TO CHILD</button>
 </div>

 <div>
  <app-child>
 </div>

子HTML:

 <div>
    <div #childelementOne>
      lot of stuff
    </div>

    <div #childelementTwo>
     another lot of stuff
    </div>

   </div>

如果所有这些 html 代码都在“相同”的 component.html 中,我会使用这个函数,但不是:

  scroll(el: HTMLElement) {
    el.scrollIntoView();
 }

那么:如何滚动到子组件中的 html 元素?

您可以为此使用@ViewChildren

项目清单:

@Component({
  selector: 'app-list-item',
  templateUrl: './list-item.component.html',
  styleUrls: ['./list-item.component.css']
})
export class ListItemComponent implements OnInit {

  @Input() list;

  constructor(private elRef: ElementRef) { }

  ngOnInit() {
  }

  scrollIntoView() {
    this.elRef.nativeElement.scrollIntoView();
  }

}

列表组件:

  @ViewChildren(ListItemComponent) viewChildren!: QueryList<ListItemComponent>;
  list = new Array(1000).fill(true)

  scrollTo() {
    this.viewChildren.toArray()[100].scrollIntoView()
  }

HTML:

<button (click)="scrollTo()">scroll to 100</button>
<app-list-item *ngFor="let item of list">
list works!
</app-list-item>

stackblitz: https ://stackblitz.com/edit/angular-ivy-6ccaav ? file = src%2Fapp%2Fapp.component.html

垫子,你的“元素”在子元素中,你想要在父元素中控制。 因此,首先使用 ViewChild 访问 child 中的元素

//in your child.component
@ViewChild("childelementOne") childelementOne;
@ViewChild("childelementTwo") childelementTwo;

然后在父母你可以做

<div>
  <button type="button" (click)="scroll(childComponent.childelementTwo)">
       TO CHILD
   </button>
</div>

<div>
  <!--see that use a template reference variable to the childComponent-->
  <app-child #childComponent></app-child>
 </div>

 scroll(el: ElementRef) {
   el.nativeElement.scrollIntoView();
 }

看看我们如何在 .html 中使用childComponent.childelementTwo childComponent是自己的组件 app-child, childComponent.childelementTwo是我们在@ViewChild获得的“变量”。 缺陷是一个 ElementRef。 您可以使用 el.nativeElement 访问 HTMLElement。 是的,使用模板引用,我们可以访问 child.component 的所有公共变量和公共函数

我创建了一个看起来像 enno 答案中的 stackblitz 的 stackblitz,但看到这是完全不同的

笔记。 您还可以在 child.component 中使用相同的 referenceVariable 并使用 ViewChildren,因此您可以将 QueryList 和索引传递给函数

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM