まず、あなたのプロジェクトにビューモデルの概念を導入することをお勧めします。 View-modelには、特定のモデルのレンダリング方法に関する情報が含まれています。あなたの場合、A
とB
の間に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
注釈をお読みください。
ng-classを使用して条件付きクラスを適用する:http://angular-craft.com/css-in-angular-2-ng-class-and-view-encapsulation/ – Walfrat