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

角度10从父组件滚动到子组件html中的元素,html,angular,scroll,angular10,Html,Angular,Scroll,Angular10,父html: <div> <button type="button" (click)="scroll(childelementTwo)">TO CHILD</button> </div> <div> <app-child> </div> 因此:如何滚动到子组件中的html元素?您可以使用@ViewChildren进行此操作 清单项目: @Componen

父html:

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

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

因此:如何滚动到子组件中的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()
  }
@ViewChildren(ListItemComponent)ViewChildren!:查询列表;
列表=新数组(1000)。填充(真)
滚动到(){
this.viewChildren.toArray()[100].scrollIntoView()
}
HTML:

滚动到100
Mat,您的“元素”在子元素中,您希望在父元素中进行控制。因此,首先使用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();
 }

给孩子
这看起来像恩诺回答中的stackblitz,但这完全不同


注意。您还可以在child.component中使用相同的referenceVariable并使用ViewChildren,这样您就可以将QueryList和index传递给函数
<button (click)="scrollTo()">scroll to 100</button>
<app-list-item *ngFor="let item of list">
list works!
</app-list-item>
//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();
 }