首页 > 解决方案 > 无法在角度项目中向@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>

谢谢你的帮助......我希望我很清楚......我只有字符串,没有要恢复的号码......

标签: javascriptangulartypescript

解决方案


@Input装饰器的语法是

bindingPropertyName: <TYPE>

您的代码中的示例 -

@Input() postLoveIts: number

推荐阅读