2016-04-18 15 views
0

角度2のサービスを使用してクラスを追加/削除できるサンプルを作成しようとしています。ここでplunkrです:私は基本的に何をやっているhttps://plnkr.co/edit/qLzgTca6Ul4W6OpBXG7w?p=previewAngular 2 Servicesを使用したクラスの切り替え

は私がサービスを使用してアプリケーションにまたがって別のセレクタ間でクラスを切り替えしようとしています、ボタンのクリックである:

import {Injectable} from "angular2/core"; 

@Injectable() 
export class AppService{ 
    background: boolean = false; //Scrolling is on by default 
} 

背景背景が変化したりべきでない場合はフラグが決定:

ComponentA:

import {Component} from 'angular2/core'; 
import {AppService} from './app.service'; 

@Component({ 
    selector: "comp-a", 
    template: ` 
     <div> 
     Component A! 
     <button (click)="onClick()">Click me</button> 
     </div> 
    ` 
}) 
export class ComponentA{ 

    constructor(private _appService: AppService){ 

    } 

    onClick(){ 
    this._appService.background = true; 
    console.log(this._appService.background); 
    } 
} 

指令C:

import {Directive} from 'angular2/core'; 
import {AppService} from './app.service'; 

@Directive({ 
    selector: "my-app", 
    host: {'[class.backgroundBlue]':'_appService.background'} 
}) 
export class DirectiveC{ 

    constructor(private _appService: AppService){ 

    } 
} 

アプリケーション:私はComponentAにボタンをComponentB変化の色をクリックしますが、なぜそれがDirectiveCためのセレクタには影響を与えません

import {Component} from 'angular2/core'; 

import {ComponentA} from './a.component'; 
import {ComponentB} from './b.component'; 
import {DirectiveC} from './c.directive'; 

@Component({ 
    selector: "my-app", 
    template: ` 
     <div> 
     App Component! 
     <comp-a></comp-a> 
     <comp-b></comp-b> 
     </div> 
    `, 
    directives: [ComponentA,ComponentB,DirectiveC] 
}) 
export class AppComponent{ 
} 

答えて

0

あなたはAppComponentのディレクティブのリストにDirectiveCを追加するのを忘れ:

directives: [ComponentA, ComponentB, DirectiveC] 

だから、ディレクティブが適用されません。

このplunkr:https://plnkr.co/edit/JwskUymdNgGTRtnzuD4s?p=previewを参照してください。

+0

まだ動作しません:( – takeradi

+0

私はここで問題はAppComponentはあなたの主なコンポーネント、つまりあなたがブートストラップするコンポーネントだと思います... –

+0

DirectiveCのセレクタをbodyタグで置き換えても動作しません。 – takeradi

関連する問題