【问题标题】:Angular2 Get reference to element created in ngForAngular2获取对在ngFor中创建的元素的引用
【发布时间】:2016-03-22 06:45:42
【问题描述】:

我将如何引用在 ngFor 循环中创建的 dom 中的元素。

例如我有一个迭代的元素列表:

var cookies: Cookie[] = [...];

<div *ngFor="#cookie of cookies" id="cookie-tab-button-{{cookie.id}}" (click)="showcookie(cookie);">Cookie tab</div>


<div *ngFor="#cookie of cookies" id="cookie-tab-content-{{cookie.id}}" ">Cookie Details</div>

我将如何引用这些 div,这样我就可以添加一个像“is-active”这样的 css 类。 还是我的方法错了。

【问题讨论】:

    标签: angular


    【解决方案1】:

    如果要添加/删除类,请使用绑定

    <div *ngFor="let cookie of cookies" [class.isActive]="someExpression" ....>
    

    <div *ngFor="let cookie of cookies" [ngStyle]="{'isActive': someExpression}" ....>
    

    具体例子:

    activeCookie:string = 'b';
    cookies:string[] = ['a', 'b', 'c'];
    
    <div *ngFor="letcookie of cookies" [class.isActive]="cookie == activeCookie" ....>
    

    如果你真的想获得参考,你可以使用

    <div #someName *ngFor="let cookie of cookies" id="cookie-tab-button-{{cookie.id}}" (click)="showcookie(cookie);">Cookie tab</div>
    
    @ViewChildren('someName') someDivs;
    
    ngAfterViewInit() { // or some event handler
      someDivs.toArray()[0].nativeElement.classList.add('isActive');
    }
    

    【讨论】:

    • 在这种情况下,表达式更容易我可以做 class.isActive = cookie.id = selectedCookieId 并将其放入组件中。谢谢,这是最简单的。
    • @GünterZöchbauer:嘿,我想从 ngFor 获得参考,我复制了上面的代码,除了在函数 ngAfterViewInit() 中添加“this”:“this.someDivs[0].nativeElement.classList.添加('isActive');“。但是,我收到一个错误:Cannot read property 'nativeElement' of undefined。如果我console.log(this.someDivs); ,则在控制台输出QueryList;如果console.log(this.someDivs);,则其类型为对象。如果console.log(this.someDivs[0]),它的输出是未定义的。
    • 添加模板变量可以使用@ViewChildren查询。
    • @GünterZöchbauer 谢谢。如果我在
      内的 (子组件选择器)上应用 *ngFor,并且子组件内有一个公共函数 playVideo()。我希望从父组件调用所有孩子的 playVideo() 来同时播放所有视频。现在,我有代码@ViewChild(ChildComponent) child: ChildComponent;this.child.playVideo(); 但是这样我只能获取一个子组件引用并让一个视频播放。你能帮帮我吗?
    • 使用@ViewChildren(ChildComponent) children : QueryList&lt;ChildComponent&gt;; ... this.children.toArray()[3].playVideo();`
    【解决方案2】:
    <style>
          .active{
              background:blue;
          }
    </style>
    
    
    
    <div [ngClass]="{active:(i==selectedIndex)}" 
         *ngFor="#cookie of cookies;#i=index"        
          id="cookie-tab-button-{{cookie.id}}"  
          (click)="showcookie(cookie,i);">Cookie tab
    </div>
    
    
    
    showcookie(val, i){
            console.log(val + i);
            this.selectedIndex=i;
    }
    

    【讨论】:

      【解决方案3】:

      你可以使用不被渲染的 ng-container:

      <ng-container *ngFor="let cookie of cookies">
        <div id="cookie-tab-button-{{cookie.id}}" (click)="showcookie(cookie);">Cookie tab</div>
      </ng-container>
      

      【讨论】:

        【解决方案4】:
        <div *ngFor="let item of items" (click)="itemClick($event.currentTarget)"></div>
        
        itemClick(dom){
          dom.style.color='red';
          // ...
        }
        

        【讨论】:

          【解决方案5】:

          另一种变化:

          在父控件中:

          // typescript
          childControls: ChildComponent[] = [];
          
          <!-- HTML -->
          <ng-container *ngFor='let period of periods'>
            <app-child [period]='period' [parent]='this'></app-child>
          </ng-container>
          

          在子控件中:

          private _parent: ParentComponent;
          @Input() set parent(value: ParentComponent) {
            this._parent.childControls.push(this);
          }
          get parent(): ParentComponent {
            return this._parent;
          }
          

          这提供了对父级中子控件的引用数组。

          【讨论】:

            猜你喜欢
            相关资源
            最近更新 更多
            热门标签