如何在组件中找到元素?

时间:2016-03-16 13:19:26

标签: angular

我想知道如何使用渲染器在组件中找到元素?

在angular1中我会去:

link = (scope, element, attributes) => {
            var outsideBox = element.find('.outside-box');
}

这会给我一个<div class="outside-box"></div>

任何指针都非常受欢迎!

2 个答案:

答案 0 :(得分:8)

我会使用其selectRootElement方法:

import {Component,Renderer} from 'angular2/core';

@Component({
  selector: 'my-app',
  template: `
    <div>
      <div class="outside-box"></div>
      <div (click)="onClick()">Click</div>
    </div>
  `
})
export class AppComponent {
  constructor(private renderer:Renderer) {
  }

  onClick() {
    var outsideBox = this.renderer.selectRootElement('.outside-box');
  }
}

请参阅此plunkr:https://plnkr.co/edit/9OJ9kr?p=preview

答案 1 :(得分:3)

我会使用Plunker - BrowserDomAdapter

import {Component,ElementRef} from 'angular2/core';
import {BrowserDomAdapter} from 'angular2/platform/browser';
//import { DOM } from 'angular2/src/platform/dom/dom_adapter';
@Component({
    selector: 'my-app',
    template: `
    <style>
      .test{
        color:green;
        background:white;
      }
    </style>
    <button (click)="add()" class="btnClass">Add New Element</button>
    `
})

export class AppComponent {
 dom:BrowserDomAdapter;
  constructor(el:ElementRef) { 
    this.dom = new BrowserDomAdapter();
    console.log(el);
  }
  add(){

      console.log( this.dom.query(".btnClass"));    
      this.dom.addClass(this.dom.query(".btnClass"),"test");
      console.log(this.el);

  }
}