How to create a component for a sibling in Angular2?

I have a search component containing a logo, search bar and routeroutlet. Performing the search proceeds to the resulting list, which is the pseudo-html described here:

<search>
  <logo></logo>
  <searchbar></searchbar>
  <result-list></result-list>
</search>

I like the style of the logo and searchbar differently on the results page, so I tried to choose a logo with :host >>> logoand an alternative /deep/from the component result-list. This does not work. Is there any way to choose siblings?

Here's a little plnkr to demonstrate the problem. http://plnkr.co/edit/Q0CLjcsftbqe0kHKrKks?p=preview Here I would like a style from resultlist logo, and searchbar- black.

+4
source share
3 answers

What you are trying basically divides the global state of the application isSearchResultList: booleaninto several components.

An obvious naive solution would be to hold the state in the corresponding common parent component and set it based on the current router output.

<search>
  <logo [isSearchResultList]="isSearchResultList"></logo>
  <searchbar [isSearchResultList]="isSearchResultList"></searchbar>
  <result-list></result-list>
</search>
+1
source

A similar solution for one of Jens Habegger using :host-context(myCssClass)and conditional. Style should be added to logoand components searchbar.

<search>
  <logo [class.myCssClass]="isSearchResultList"></logo>
  <searchbar [class.myCssClass]="isSearchResultList"></searchbar>
  <result-list></result-list>
</search>
:host-context(.myCssClass) {
  color: black;
 }
0
source

ngClass .

notification.service.ts

import {Injectable, EventEmitter} from '@angular/core';

@Injectable()
export class NotificationService {
  private static _emitters: { [ID: string]: EventEmitter<any> } = {};

  static get(ID: string): EventEmitter<any> {
    if (!this._emitters[ID]) {
      this._emitters[ID] = new EventEmitter();
    }
    return this._emitters[ID];
  }
}

.

bar.component.ts

import { NotificationService } from 'notification.service';
....
ngOnInit() {
      NotificationService.get('barcomponent').emit(true);
  }
  ngOnDestroy() {
      NotificationService.get('barcomponent').emit(false);
  }
...

.

foo.component.ts

import { NotificationService } from 'notification.service';
....
ngOnInit() {
    NotificationService.get('barcomponent').subscribe(value => {
        this.activateStyle = value;
    });
  }
....

ngClass

foo.component.html

....
<div [ngClass]="{'my-css-class':activateStyle}">
  ...
</div>
....
0
source

Source: https://habr.com/ru/post/1665300/


All Articles