我查看了几个相关的帖子和文档,但仍然无法从@ViewChild获得预期的行为.
最终,我正在尝试设置div的滚动位置.此元素不是组件,而是HTML中的普通div.
为了实现这一点,我试图使用@ViewChild来获取我需要的DOM元素,并设置其滚动值.(顺便说一句,如果你知道一个更好的方法来实现这个没有@ViewChild(或jQuery),将非常感谢答案!)
目前,@ ViewChild只返回undefined.经历一些虚拟检查: - 我在AfterViewInit中访问我的元素 - 我没有任何其他指令,如*ngIf或*ngFor在这个元素上.
这是控制器:
import { Component, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'portfolio-page',
templateUrl: './portfolio-page.component.html',
styleUrls: ['./portfolio-page.component.scss']
})
export class PortfolioPageComponent implements AfterViewInit{
@ViewChild('gallery-container') galleryContainer: ElementRef;
ngAfterViewInit(){
console.log('My element: ' + this.galleryContainer);
}
}
Run Code Online (Sandbox Code Playgroud)
和模板:
<div id='gallery-container' class='gallery-image-container'>
<div class='gallery-padding'></div>
<img class='gallery-image' src='{{ coverPhotoVm }}' />
<img class='gallery-image' src='{{ imagepath }}' *ngFor='let imagepath of imagesVm' />
</div>
Run Code Online (Sandbox Code Playgroud)
我的输出很简单:我的元素:未定义.
如您所见,我目前正在尝试按ID访问元素,但也尝试过类名.任何人都可以提供有关ViewChild选择器查询期望的更多详细信息吗?
我还看到了一个示例,其中散列'#'用作@ViewChild使用的选择器标识符 - 但是这会导致我使用#gallery-container导致模板解析错误.
我想不出任何可能在这里错误的事情.感谢所有帮助,谢谢!
完整代码可在此处获取:https://github.com/aconfee/KimbyArting/tree/master/client/KimbyArting/components/portfolio-page
我正在尝试在Angular2中构建一个列表组件,它获取组件用户的项目字段的项目,列和模板.所以我试图使用ngTemplateOutlet和ngOutletContext(我读过的是实验性的).但我无法让它发挥作用.
这是一个简化的组件,用于演示我要做的事情:
<div *ngFor="let item of items>
<span *ngFor="let column of columns>
<template [ngOutletContext]="{ item: item }"
[ngTemplateOutlet]="column.templateRef"></template>
</span>
</div>
Run Code Online (Sandbox Code Playgroud)
以下是组件的用法:
<my-component [items]="cars" [columns]="carColumns">
<template #model>{{item.model}}</template>
<template #color>{{item.color}}</template>
<template #gearbox>{{item.gearbox}}</template>
</my-component>
Run Code Online (Sandbox Code Playgroud)
以下是示例数据:
cars = [
{ model: "volvo", color: "blue", gearbox: "manual" },
{ model: "volvo", color: "yellow", gearbox: "manual" },
{ model: "ford", color: "blue", gearbox: "automatic" },
{ model: "mercedes", color: "silver", gearbox: "automatic" }
];
carColumns = [
{ templateRef: "model" },
{ …Run Code Online (Sandbox Code Playgroud)