LoginSignup
22
22

More than 5 years have passed since last update.

Angular2で階層的DIを使う

Posted at

Angular2でとっても便利だと思ったのは、DI。コンポーネントの階層に応じて代入することができます。

サンプル

バージョン

Angular2 beta.9

使い方

注入されるクラスに @Injectable() を設定する

@Injectable()
export class MyData {
    public title:string = "サンプルテキスト";
}

注入したい対象のクラスのアノテーションに providers: [クラス名] を記述する

@Component({
    selector: 'my-foo',
    template: `
        <h2>FooComponent</h2>
        <my-hoge></my-hoge>
        <my-piyo></my-piyo>
    `,
    providers: [MyData],
    directives: [HogeComponent, PiyoComponent]
})
class FooComponent {
    constructor(private myData:MyData) {
    }
}

このコンポーネントにぶら下がる子供のコンポーネントは、providersを設定しなくても、コンストラクターで受け取ることができます。

@Component({
    selector: 'my-hoge',
    template: '<p>見出し : {{myData.title}}</p>'
})
class HogeComponent {
    constructor(private myData:MyData) {
    }
}

以上。簡単ですね。神機能です!

22
22
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
22