Angular 2: input variable in component is not updated after call

Welcome StackOverflow!

I am having problems with my code. As you can see, I want to be able to call a line with a set width (bootstrap format), since I do not want to enter a class every time.

So, I thought about the following:

import { Component, Input } from '@angular/core'; @Component({ moduleId: module.id, selector: 'content', template: ` <div class="row"> <div [ngClass]="contentClass" id="content" [ngStyle]="{ 'color': 'black', 'font-size': '20px' }"> <ng-content></ng-content> </div> </div>`, styleUrls: ['content.stylesheet.css'] }) export class ContentComponent { @Input() rowWidth = "12"; contentClass=(("col-lg-" + this.rowWidth)+(" col-sm-" + this.rowWidth)+(" col-xs-" + this.rowWidth)); } 

But as soon as I call the component from another component, it does not work the way I want.

 <banner bannerHeight="300px"></banner> <!-- This works --> <content rowWidth="6"></content> <!-- This doesn't --> 

If I used, for example,

 <content [ngStyle]="{'color': 'black'}"></content> 

The operation completes successfully. Directives and imports are set correctly in the parent component.

So here is my question: how do I get it to work the way I want it?

+5
source share
1 answer

This does not work (as you want, I assume that you mean that your contentClass has rowWidth of 12 ) because your contentClass is executed before the template is initialized.

You need to implement OnInit and use ngOnInit to set the contentClass to your rowWidth input:

 export class ContentComponent implements OnInit{ @Input() rowWidth = 12; contentClass:string; ngOnInit():any { this.contentClass = (("col-lg-" + this.rowWidth)+(" col-sm-" + this.rowWidth)+(" col-xs-" + this.rowWidth)); } } 

With <content [rowWidth]="6"></content> your element will have col-lg-6 col-sm-6 col-xs-6 instead of 12 , given as its css classes.

+4
source

All Articles