Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/409.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何为Angular2+;中的元素设置*ngFor锚定;?_Javascript_Html_Angular_Scroll_Ngfor - Fatal编程技术网

Javascript 如何为Angular2+;中的元素设置*ngFor锚定;?

Javascript 如何为Angular2+;中的元素设置*ngFor锚定;?,javascript,html,angular,scroll,ngfor,Javascript,Html,Angular,Scroll,Ngfor,有一个组件,其项显示为*ngFor。我的目标是使用锚点3向下滚动到元素 守则: @Component({ selector: 'my-app', template: ` <button (click)="scroll(3)">scroll 2</button> <li *ngFor="let item of itemList; let i = index" [attr.data-index]="i">{{i}} {{item}}<

有一个组件,其项显示为*ngFor。我的目标是使用锚点3向下滚动到元素

守则:

@Component({
  selector: 'my-app',
  template: `
    <button (click)="scroll(3)">scroll 2</button>
    <li *ngFor="let item of itemList; let i = index" [attr.data-index]="i">{{i}} {{item}}</li>
  `,
})
class HomeComponent {
    text = 'foo';
    testObject = {fieldFirst:'foo'};
    itemList = [
       //...
    ];

    scroll(el: HTMLElement) {
        el.scrollIntoView();
    }
}
@组件({
选择器:“我的应用程序”,
模板:`
卷轴2
{{{i}}{{item}
`,
})
类HomeComponent{
text='foo';
testObject={fieldFirst:'foo'};
项目列表=[
//...
];
滚动(el:HTMLElement){
el.scrollIntoView();
}
}
有一个jsfiddle

我想不出如何为它设置取消锁定?

试试看

    <button (click)="scroll('3')">scroll to 3</button>
    <li *ngFor="let item of itemList; let i = index" [attr.data-index]="i" [attr.id]="i">{{i}} -->  {{item}}</li>
    <div #target>target</div>

您可以在
li
元素上定义一些模板变量

滚动2
{{i}{{item}
目标
并在组件中检索这些元素,如下所示

@ViewChildren('elements')列表项:QueryList

最后将您的
滚动
方法更改为

scroll(id) {
    const el = this.listItems.toArray()[id].nativeElement;
    el.scrollIntoView();
}

@布兰登:小提琴似乎很好用。你能解释清楚吗。它适用于
id=“0”
@Brandon::D hahadid您是否尝试我的建议答案?
scroll(id) {
    const el = this.listItems.toArray()[id].nativeElement;
    el.scrollIntoView();
}