首页 文章

在Angular中单击事件中访问elementRef

提问于
浏览
0

我在Component中定义了字符串列表,它在视图中呈现如下:

<span  class="one" (click)='do($event, index, item)' 
*ngFor="let item of result;let index = index"  >{{item}} </span>

点击每个项目后,我想在该项目后添加div元素:

clickedSpan.insertAdjacentHTML('beforeend', '<div >Hi!</div>');

如何在 do 函数中访问 elementRef ?或者是否有其他解决方案来处理由ngFor呈现的渲染 Span ?

2 回答

  • 0

    我模板你可以在span标签中创建一个像“#addDivElement”这样的变量

    您可以使用在组件中访问这些变量

    @ViewChild('addDivElement') and you can do render the HTML element as you want 
    
    import { Component, ViewChild, ElementRef, Renderer} from '@angular/core';
    
    @Component({
        selector: 'my-app',
        templateUrl: '/app/angular/app.angular.core.html'
    })
    export class AppComponent {
    
        @ViewChild('addDivElement')
        public addElement: ElementRef;
    
        public constructor(private rendere: Renderer) {
    
        }
    
        public arrayData = ["Item1", "Item2", "Item3"];
    
        public doSomething(event, index, item) {
            this.addElement.nativeElement.insertAdjacentHTML('beforeend', '<div class="two">two</div>');
    
        }
    }
    
  • 0

    试试这个

    do(event, index, item) {
              this.result.splice(index, 0, 'Hi!');
          }
    

相关问题