Skip to content

Instantly share code, notes, and snippets.

@endash
Last active September 25, 2015 11:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save endash/a78c838c3ec5b984dedf to your computer and use it in GitHub Desktop.
Save endash/a78c838c3ec5b984dedf to your computer and use it in GitHub Desktop.
Angular 2 tips

Misc

  • Use single quotes ("'foo'") when using a directive to get a string literal

Components

  • When styling a component, the component's root element can be matched with the :host selector

  • Default bindings on the component level, including class names, can be set via the host hash on the @Component annotation:

      @Component({
          selector: 'my-component',
          host: {
              '[class]': 'foo'
          }
      })

* To inject a service into a component and have it saved as a property three things are required:
  1. **The service must be in a `viewBindings` (`@component({viewBindings:[]})`) property** either on the component itself or above it in the hierarchy (by default). Where this is defined determines when it gets instantiated, so many components injecting a service specified in a common ancestor will get the same instance.
  2. **The target component's construct should have a `public` argument for the class**, e.g. `constructor(public fooService: FooService)`. There doesn't need to be a corresponding property on the class, and the constructor isn't responsible for assigning the service to a property manually. (This is a feature of the Typescript language, and the behaviour applies to all classes—you can still manually declare and assign the properties if you'd like, but if you do you have to do both).
  3. **In both (or just the one) files, the service needs to be imported**. This isn't specific to injecting services, but it can be forgotten when managing injections across multiple files.

## Services

* To inject a dependency into a service use the `@Injectable()` decorator 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment