加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 17:35:22 所属栏目:安全 来源:网络整理
导读:你好StackOverflow的人! 我的代码遇到了一些麻烦.如您所见,我希望能够调用具有设置宽度(引导格式)的行,因为我不想每次都输入类. 所以我想到了一种方法如下: import { Component,Input } from '@angular/core';@Component({ moduleId: module.id,selector:
你好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类.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读