你好StackOverflow的人!
我的代码遇到了一些麻烦.如您所见,我希望能够调用具有设置宽度(引导格式)的行,因为我不想每次都输入类.
所以我想到了一种方法如下:
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有一个rowWidth为12),因为你对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 set作为其css类.