Rohith Murali Rohith Murali - 4 months ago 42
CSS Question

How to fix when angular 2 component take full width of the page?

My angular 2 components are taking full width of the page.
When I limit the component width, its margin is stretched to full width.
So I cannot bring other components beside this. How can I limit the width of components?
I tried display: inline, but no use.Still the component takes full width allowing nothing to come beside this.

import { Component } from '@angular/core';
import { Item } from './../item';
import { ItemComponent } from './ItemComponent';

@Component({
selector: 'Item-Set',
directives: [ItemComponent],
template: '<div class="singleItem" *ngFor="let eachItem of itemList"><Item></Item></div>'
})

export class ItemSet{
itemList: Item[];
constructor(){
this.itemList=ItemList;
}
}


In style sheet

.singleItem{
width:300px;
}

Answer

You need to add the CSS to set the width at the correct place. In your example would that be the styles parameter of ItemSet or Item like

Plunker example

Either on the ItemComponent with the :host selector (self):

@Component({
  selector: 'Item',
  template: '<div>Item</div>',
  styles: [':host {display: block; border: solid 1px red; width: 300px;}']
})
export class ItemComponent{}

or the parent component with .singleItem as selector

@Component({
  selector: 'Item-Set',
  directives: [ItemComponent],
  styles: [`
    .singleItem{width:300px;}
    :host {display: block; border: solid 1px green;}`
  ]
  template: '<div class="singleItem" *ngFor="let eachItem of itemList"><Item></Item></div>'
})
export class ItemSet{
  itemList = ['a', 'b', 'c', 'd'];
})
Comments