Angular 2: Component 中的输入变量一旦调用就不会更新

Angular 2: Input variable in Component does not update once called

大家好 Whosebug 的朋友们!

我的代码有些问题。如您所见,我希望能够调用具有设置宽度(bootstrap 格式)的行,因为我不想每次都键入 class。

于是我想到了一个办法,就是:

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));
}

但是一旦我从另一个组件调用该组件,它就无法按我想要的方式工作。

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

如果我使用例如

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

操作成功。指令和导入在父组件中设置正确。

所以这是我的问题:如何让它按照我想要的方式工作?

它不起作用(你想要的方式,我假设你的意思是你的 contentClass 有一个 rowWidth12)因为你分配给 contentClass在模板实际初始化之前创建。

您必须实施 OnInit 并使用 ngOnInit 设置 contentClass 并分配给您的 rowWidth 输入:

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));
    }
}

使用 <content [rowWidth]="6"></content>,您的元素将 col-lg-6 col-sm-6 col-xs-6 而不是 12 设置为其 css 类.