如何在组件中找到元素?

uks*_*ksz 2 angular

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

在angular1我会去:

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

哪个给我一个回报 <div class="outside-box"></div>

任何指针都非常受欢迎!

Thi*_*ier 10

我会用它的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');
  }
}
Run Code Online (Sandbox Code Playgroud)

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

  • 是的,我认为在构造函数中调用太早,因为稍后会呈现模板.`ngOnInit`会是一个更好的地方,因为可以多次调用`ngOnChanges`.但是你第一次调用它是正确的,它在'ngOnInit`之前...... (2认同)