Skip to content

Instantly share code, notes, and snippets.

@bennadel
Created June 22, 2016 12:18
ChangeDetectorRef Is A Special Dependency In Angular 2 RC 3
// Import the core angular services.
import { Component } from "@angular/core";
// Import the application components and services.
import { MyCounterComponent } from "./counter.component";
import { TestChangeDetectorDirective } from "./test-change-detector.directive";
@Component({
selector: "my-app",
directives: [ MyCounterComponent, TestChangeDetectorDirective ],
template:
`
<p>
<a (click)="incrementCounter()">Increment counter</a>
</p>
<my-counter [count]="counter" testChangeDetector></my-counter>
`
})
export class AppComponent {
// I hold the counter which is being passed into the Counter component(s).
public counter: number;
// I initialize the component.
constructor() {
this.counter = 0;
}
// ---
// PUBLIC METHODS.
// ---
// I increment the counter by one.
public incrementCounter() : void {
this.counter++;
}
}
// Import the core angular services.
import { ChangeDetectorRef } from "@angular/core";
import { Component } from "@angular/core";
@Component({
selector: "my-counter",
inputs: [ "count" ],
// Here, we are providing a test value to demonstrate that non-ChangeDetectorRef
// dependencies can be provided by the component and required by a sibling directive.
providers: [
{
provide: "ProviderTest",
useValue: "Provided by Counter Component."
}
],
template:
`
Count: {{ count }}
`
})
export class MyCounterComponent {
// I hold the current count. This is an injected property.
public count: number;
// I initialize the component.
constructor( changeDetectorRef: ChangeDetectorRef ) {
console.group( "MyCounter Component" );
console.log( changeDetectorRef );
console.groupEnd();
}
}
// Import the core angular services.
import { ChangeDetectorRef } from "@angular/core";
import { Directive } from "@angular/core";
import { Inject } from "@angular/core";
import { Self } from "@angular/core";
@Directive({
selector: "[testChangeDetector]"
})
export class TestChangeDetectorDirective {
// I initialize the directive.
constructor(
@Self() changeDetectorRef: ChangeDetectorRef,
@Self() @Inject( "ProviderTest" ) providerTest: string
) {
console.group( "TestChangeDetector Directive" );
console.log( changeDetectorRef );
console.log( providerTest );
console.groupEnd();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment