5

Hello people of StackOverflow!

I am having some trouble with my code. As you can see, I want to be able to call a row with a set width (bootstrap format), as I don't want to type the class every time.

So I thought of a way which is 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 once I call the component from another component, it's not working 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 succeeds. The directives and imports are set correctly in the parent component.

So here is my question: How do I make it work the way I want it to?

1 Answer 1

4

It doesn't work (the way you want, i assume you mean that your contentClass has a rowWidth of 12) because your assignment to contentClass is made before the template is actually initialized.

You have to implement OnInit and use ngOnInit to set the contentClass with the assignment 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 then have col-lg-6 col-sm-6 col-xs-6 instead of 12 set as its css classes.

Sign up to request clarification or add additional context in comments.

2 Comments

That did the trick! I totally forgot about the lifecycle hooks.. rookie mistake. So as this did the trick for the contentClass, would it be best practice to implement such a thing for every input variable or only when there is processing time spent on it (for example a calculation or concatenation)?
Well, if you want to use your input at time of initialization, then yes (which you want most of the time) you need a lifecycle hook.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.