Eggy
Eggy

Reputation: 4174

Using flexbox with angular 2 components

I want to update visual side(grid, colors) of my angular 2 application. Old layout was build with bootstrap 4, which I don't really need anymore. I decided to go for plain css3, and build grid with flexbox. I made a preview of this grid on codepen.

However implementation in project is hard and I am now stuck. Let's consider an example:

import {Component} from 'angular2/angular2';


@Component({
  selector: 'some-component',
  template: `
    <aside class="col-4 main-aside"></aside>
    <section class="main-section center"></section>
  `
})
export class SomeComponent { }

If I bootstrap this component within, for example .container I may get this result:

<body>
  <!-- .container is flex parent -->
  <div class="container">
    <some-component>
      <!-- .main-aside and .main-section should be flex children -->
      <aside class="main-aside"></aside>
      <section class="main-section center"></section>
    </some-component>
  </div>
</body>

As you can see the flex chain parent -> child is broken because of component "selector" between them. I menaged to fix this by adding styles: display: flex; width: 100%; to component selector from chrome dev tools, however I don't know how to make this work from code perspective nor is it the best way to do so.

I would really appreciate any help, because I have no idea how to fix this with the exception of not using flexbox.

I am using angular 2.0.0-alpha.44

And yes, I am aware of angular's alpha state.

Upvotes: 18

Views: 15502

Answers (3)

Jiayi Hu
Jiayi Hu

Reputation: 2270

:host selector solves the problem but you end using it very often in many components.

I used instead the following global CSS:

.row > * {
  display: flex;
  flex-basis: 100%;
}

Upvotes: 1

Philip
Philip

Reputation: 24315

The angular team released their own flex-layout package, so you don't need to write it by your self anylonger:

https://github.com/angular/flex-layout

Upvotes: 0

Eggy
Eggy

Reputation: 4174

I fixed this issue by adding styles to component. For example:

:host {
  display: flex;
}

:host {} was the key.

Upvotes: 45

Related Questions