2017-07-04 14 views
0

私はコンポーネントAを5枚持っています。唯一の1画像は色を持っており、クリック可能で、他の4は、このCSSクラスAngular2でサービス経由でコンポーネントにCSSを追加できますか?

.not_opened{ 
    -webkit-filter: grayscale(85%); 
} 

の助けを借りて、灰色され、クリックできません。

私は最初の画像をクリックすると、私は、(それは別の部品ではなく、子供や親であるのでAは、消える)componentBにコンポーネントを変更するには、新しい二component Bでいくつかの操作を行い、その後、私はボタンをクリックして、どの私をcomponent Aに返します。すべてが同じままですが、私は灰色ではない2つの画像を作成したいので(画像2からnot_openedしたこのクラスを削除/変更してください)、次に画像2をクリックすると3番目の画像に行きますcomponent Cそして3番目の画像現在はグレーでクリック可能ではありません。

どうすればこのようにすることができますか? 最初に考えたのは4つの異なるコンポーネントを作ることでしたが、それぞれ独自のCSSスタイルシートを使っていましたが、別の方法がありますか? サービスの助けを借りて何とかしていますか? アドバイスをお願いしますか?

+0

ng-classを使用して条件付きクラスを適用する:http://angular-craft.com/css-in-angular-2-ng-class-and-view-encapsulation/ – Walfrat

答えて

0

まず、あなたのプロジェクトにビューモデルの概念を導入することをお勧めします。 View-modelには、特定のモデルのレンダリング方法に関する情報が含まれています。あなたの場合、ABの間にArray<ImageViewModel>のようなものを渡すことができます。あなたがあなたのケースに適して見つけた場合は、いくつかのサービスを介してこのデータを渡すこともできますし、親コンポーネントを使用することができ、例えば:

親コンポーネントテンプレート:

<component-a [images]="images" *ngIf="active === 'a'" (onImageSelected)="handleImageSelected($event)"></component-a> 
<component-b [images]="images" *ngIf="active === 'b'" (onSettingsEditCompleted)="handleSettingsEditCompleted()"></component-b> 

親コンポーネントコード:

.... { 
    images: Array<ImageViewModel> = []; 
    active: string = "a"; 

    constructor(private _service: ImageService) { 
     // Lets imagine that service returns array of image urls. 
     this._service.fetchImages().subscribe((urls) => { 
      this.images = urls.map(url => ({src: url, disabled: true})); 
      if (this.images.length > 0) { 
       this.images[0].disabled = false; 
      } 
     }); 
    } 

    handleImageSelected(image: ImageViewModel) { 
     this.active = "b"; 
     console.log("Image selected", image); 
    } 

    handleSettingsEditCompleted() { 
     this.active = "a"; 
    } 
} 

そしてImageViewModelは何かのように:

interface ImageViewModel { 
    src: string; 
    disabled: boolean; 
} 

componentAにある[ngClass]ディレクティブを使用して画像の可用性を変更します。

ComponentAテンプレート:

<img *ngFor="let image of images" [src]="image.src" [ngClass]="{'not-opened': image.disabled}" (click)='!image.disabled && handleImageSelected(image)'/> 

ComponentAスタイル:

.not-opened { 
    filter: grayscale(85%); // Why do you use -webkit version only? 
    -webkit-filter: grayscale(85%); 
}   

ComponentAコード:

... { 
    @Output() 
    onImageSelected = new EventEmitter<ImageViewModel>(); 
    @Input() 
    images: Array<ImageViewModel> = []; 

    handleImageSelected(image: ImageViewModel) { 
     this.images[1].disabled = false; 
     this.onImageSelected.emit(image); 
    } 
} 

何かが明確でない場合には角度のドキュメントで約@Input@Output注釈をお読みください。

関連する問題