我读过很多关于这方面的文章和文档,但他们似乎都没有采取我想要做的方法。
我有一个类别项数组,在其中我有一个嵌套数组的上述类别产品。就像这样。
<ng-container *ngFor="let menu of menuList">
<ng-container *ngFor="let item of menu.catItem" >
<div class="card" #cmp >
just to demonstrate
<button class="animateIt(cmp)"> click to animate </button>
</div>
</ng-container>
</ng-container>当用户单击我想要添加某种动画的按钮时,我可以在没有任何问题的情况下做到这一点,但问题是,如果不使用任何额外的JavaScript库,我就想不出解决这个问题的方法。
我已经尝试将ViewChildren添加到组件中。以及打印元素的函数。
@ViewChildren('cmp') components: QueryList<ElementRef>;
constructor(private renderer: Renderer2){}
animateIt(cmp:ElementRef){
console.log(cmp);
this.renderer.setAttribute(cmp.nativeElement, 'class', 'myClass');
}函数中的第二行给出了一个错误,因为没有定义cmp.nativeElement,这是预期的,因为它所做的只是获取div的内容,然后只打印它而不生成ElementRef对象。有什么办法,我可以做到这一点,只用角度或只是JS?
发布于 2020-12-17 09:12:08
通过使用普通的JS完成了这段代码
animateIt(cmp:ElementRef){
this.el.nativeElement = cmp;
let element = document.createElement('div');
element = this.el.nativeElement.cloneNode(true);
element.style.position = "absolute";
element.style.top = this.el.nativeElement.offsetTop + 'px';
element.style.left = this.el.nativeElement.offsetLeft + 'px';
let parent = document.getElementById("parent");
parent.appendChild(element);
}发布于 2020-12-17 07:09:29
我认为您需要在ngAfterViewInit生命周期中检索元素,如下所示:
ngAfterViewInit() {
this.cmp.changes.subscribe(() => {
console.log('changed');
})
}https://stackoverflow.com/questions/65335996
复制相似问题