微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决从父组件到子组件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传递给函数

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?