Angular2 - Class - ElementRef

  • An ElementRef is created for each element in the Template that contains a Directive, Component or data-binding.
  • An ElementRef is backed by a render-specific element. In the browser, this is usually a DOM element.

Template、Directive里用ElementRef 知道,data-binding怎么用还不清楚

data-binding指的是 #ref

import {Component,ElementRef,ViewChild} from 'angular2/core'

@Component({
selector: 'app',
template: `
<h1 #title>App</h1>
`
})
export class App {

@ViewChild('title') title:ElementRef;

ngAfterViewInit(){
console.log(this.title);
}

}

能不用这个就不用,一般操作DOM用Renderer

export abstract class ElementRef {
/**
* The underlying native element or `null` if direct access to native elements is not supported
* (e.g. when the application runs in a web worker).
*
* <div class="callout is-critical">
* <header>Use with caution</header>
* <p>
* Use this API as the last resort when direct access to DOM is needed. Use templating and
* data-binding provided by Angular instead. Alternatively you take a look at {@link Renderer}
* which provides API that can safely be used even when direct access to native elements is not
* supported.
* </p>
* <p>
* Relying on direct DOM access creates tight coupling between your application and rendering
* layers which will make it impossible to separate the two and deploy your application into a
* web worker.
* </p>
* </div>
*/
get nativeElement(): any { return unimplemented(); }
}

这个nativeElement 是DOM对象不是Jq对象,举例

<result class="col-xs-2 col-xs-offset-1 resultItem itemSpace" _ngcontent-hev-3="" _nghost-hev-4="">
<div class="row" _ngcontent-hev-4="">
<div class="col-xs-6" rotate="" _ngcontent-hev-4="">chenboxiang</div>
<div class="col-xs-6" _ngcontent-hev-4="">
<img class="img-responsive" rotate="" _ngcontent-hev-4="" src="https://avatars.githubusercontent.com/u/1421876?v=3">
</div>
<div class="col-xs-8" _ngcontent-hev-4="">
<button class="btn btn-default btn-lg" rotate="" type="button" _ngcontent-hev-4="">
<span aria-hidden="true" class="glyphicon glyphicon-star" _ngcontent-hev-4=""></span> 20
</button>
</div>
<div class="col-xs-4" style="margin-top:20px;" _ngcontent-hev-4="">
<a _ngcontent-hev-4="" href="https://github.com/chenboxiang/fdfs-client"> Watching</a>
</div>
</div>
</result>