首页 > 解决方案 > 输入 Angular 组件抛出错误

问题描述

我是角度的新手。

在项目中,我创建了一个名为 button 的组件,并在button.components.ts文件中添加了Inputon的代码,import { Component, OnInit, **Input** } from '@angular/core';然后在 button.component.ts 构造函数上方添加了以下代码

@Input() text:string;

但它在text一词上给我一个错误,错误说,

属性 'text' 没有初始化器,也没有在构造函数中明确分配

button.component.ts的完整代码如下,

import { Component, OnInit, Input } from '@angular/core';

   @Component({
   selector: 'app-button',
   templateUrl: './button.component.html',
   styleUrls: ['./button.component.css']
   })
   export class ButtonComponent implements OnInit {
  
   @Input() text:string;

   constructor() { }

   ngOnInit(): void {
   }

   }

当我在构造函数中初始化文本值时,参考@Rohith V 共享的链接,它会在我调用此按钮组件的另一个组件上引发错误。

在名为 header.component.html 的组件上向我抛出错误

<header>
<h1>{{title}}</h1>
<app-button color="green" **text**="Add"></app-button>
</header>

错误说

类型“字符串”不可分配给类型“任何 []”

更新后的 button.component.ts 如下,

import { Component, OnInit, Input } from '@angular/core';

   @Component({
   selector: 'app-button',
   templateUrl: './button.component.html',
   styleUrls: ['./button.component.css']
   })
   export class ButtonComponent implements OnInit {
  
   @Input() text:any[];

   constructor() {
   this.text = [];
   }

   ngOnInit(): void {
   }

   }

标签: angular

解决方案


推荐阅读