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

问题描述

父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.childelementTwochildComponent是自己的组件子应用程序,childComponent.childelementTwo是我们在@ViewChild中获得的“变量”。通过缺陷是ElementRef。您可以使用el.nativeElement进入HTMLElement。是的,使用模板引用,我们可以访问您孩子的所有公共变量和公共功能。component

我创建了a stackblitz,看起来像enno的答案中的堆叠闪电一样,但看到的是完全不同的

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...