javascript - 无法在角度项目中向@input 声明数字
问题描述
我刚从角度开始,只是想声明一个输入。我期待一个数字而不是数组中的对象中的字符串,但我无法得到它,我不明白出了什么问题。当我向 loveIts 值声明一个数字时(例如 => loveIts: 3),它崩溃了。这是我的信息:
Error: src/app/app.component.html:28:10 - error TS2322: Type 'string | number' is not assignable to type 'string'.
Type 'number' is not assignable to type 'string'.
28 [postLoveIts]="post.loveIts"
~~~~~~~~~~~
src/app/app.component.ts:5:16
5 templateUrl: './app.component.html',
~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component AppComponent.
这是我的代码:
应用程序组件
> import { Component } from '@angular/core';
>
>
> @Component({ selector: 'app-root', templateUrl:
> './app.component.html', styleUrls: ['./app.component.scss'] })
> export class AppComponent {
> posts = [
> {
> title: "First Post",
> content: "StringString1String1String1String1",
> loveIts: "3",
> created: new Date()
> },
> {
> title: "Second post",
> content: "String2String2String2String2",
> loveIts: "6",
> created: new Date()
> },
> {
> title: "Third Post",
> content: "String3String3String3String3String3",
> loveIts: "18",
> created: new Date()
> }, ];
post-list.component.ts
import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'app-post-list',
templateUrl: './post-list.component.html',
styleUrls: ['./post-list.component.scss']
})
export class PostListComponent implements OnInit {
@Input() postTitle = 'string';
@Input() postContent = 'string';
***@Input() postLoveIts = 'number';***
@Input() postCreated = new Date;
constructor() { }
ngOnInit(): void {
}
addOne() {
let postLoveIts = this.postLoveIts ;
}
}
即使对于字符串,我也不能将它声明为像 @Input() postLoveIts = number 这样的数字,而且似乎在 app.component 我不能像这样声明它 loveIts: 18 (例如),vs code给我此错误:“消息”:“'数字'仅指一种类型,但在这里用作值。”
这是我的 app.component.html
<div class="container">
<div class="row">
<div class="col-xs-12">
<h2>Mes posts</h2>
<ul class="list-group">
<app-post-list *ngFor="let post of posts"
[postTitle]="post.title"
[postContent]="post.content"
[postLoveIts]="post.loveIts"
[postCreated]="post.created"
></app-post-list>
</ul>
</div>
</div>
</div>
谢谢你的帮助......我希望我很清楚......我只有字符串,没有要恢复的号码......
解决方案
@Input
装饰器的语法是
bindingPropertyName: <TYPE>
您的代码中的示例 -
@Input() postLoveIts: number
推荐阅读
- python - 如何将 Python 脚本转换为 Python 应用程序?
- react-native - “InvalidStateError:DOM 异常 11:此事务已完成。”
- c++ - 在 C++ 中不使用 POW 处理负指数
- c# - 使用 aruco V3 时,ESP 上的 DLL 导入失败未在函数调用中正确保存
- highcharts - 使用数据绑定 PowerBI 的 Highcharts 自定义视觉效果
- node.js - 在 Raspberry Pi 上部署 Nodejs Telegram 机器人
- flutter - 如何使用 moor_flutter 包计算 sqlite db 表中的记录?
- javascript - 如何在反应钩子中调用构造函数逻辑?
- javascript - Angular Ionic 4 如何将变量从 page.html 传递到 page.ts
- amazon-cognito - 使用 SAML 2 更新令牌问题的 Okta 作为 IdP 的 Cognito