简体   繁体   English

将值传递给组件 html 的 Angular 7 问题

[英]Angular 7 issue with passing value to components html

I am trying something very simple but I keep getting an error:我正在尝试一些非常简单的事情,但我不断收到错误消息:

Here is the code:这是代码:

app.component.html应用程序组件.html

<div class="col-md-{{myvalue}}">stuff here</div>

app.component.ts app.component.ts

myvalue: string;


ngOnInit() {
    this.myvalue('6');
}

For some reason it's giving me this error:出于某种原因,它给了我这个错误:

Cannot invoke an expression whose type lacks a call signature.无法调用类型缺少调用签名的表达式。 Type 'String' has no compatible call signatures. “字符串”类型没有兼容的调用签名。

What I'm I doing wrong here?我在这里做错了什么?

you have to assign value to string as this:您必须为字符串赋值,如下所示:

myvalue: string;


ngOnInit() {
    this.myvalue = 6;
}

Try this,尝试这个,

app.component.html应用程序组件.html

<div [ngClass]="myvalue">...</div>

app.component.ts app.component.ts

myvalue: string;
ngOnInit() {
    this.myvalue = 'col-md-'+'6'; //concatenate your value as string here
}

If you want to pass data using with function , you can achieve it by using this approach,如果你想使用 with function传递数据,你可以使用这种方法来实现它,

myvalue: string;
ngOnInit() {
  this.setValue('6');
}

setValue(val: string){
    this.myvalue = 'col-md-'+val; //concatenate your value as string here
}

I also recommend you to read this documentation, https://angular.io/api/common/NgClass我还建议您阅读此文档, https://angular.io/api/common/NgClass

I wouldn't recommend @shadowman_93's solution.我不会推荐@shadowman_93 的解决方案。 We have property binding for a reason.我们有属性绑定是有原因的。 There's no reason to change CSS decorators in your component for this.没有理由为此更改组件中的 CSS 装饰器。 It makes more sense to keep 'col-md' in your template, that way if you ever need to change it you will find it in an intuitive place, not in a string literal in your component.在你的模板中保留 'col-md' 更有意义,这样如果你需要改变它,你会在一个直观的地方找到它,而不是在你的组件中的字符串文字中。 Thats just bad design.那只是糟糕的设计。

Strings are not functions.字符串不是函数。 You are setting your string as if you are calling a set function for it.您正在设置字符串,就像为它调用 set 函数一样。 Strings in Typescript work like strings in pretty much every other language, so Typescript 中的字符串在几乎所有其他语言中都像字符串一样工作,所以

ngOnInit() {
    this.myvalue = '6';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM