angular - 输入 Angular 组件抛出错误
问题描述
我是角度的新手。
在项目中,我创建了一个名为 button 的组件,并在button.components.ts
文件中添加了Input
on的代码,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 {
}
}
解决方案
推荐阅读
- c# - 如何在 C# 中将字符串拆分为两个单独的变量
- c++ - system() 不适用于修改命令行提示符
- visual-studio-code - 如何修复 JSX 元素“html”在测试文件的 Visual Studio Code 中没有相应的结束标记
- c++ - 外部整数未正确传递给 std::thread 中的 lambda 表达式
- sql - 关于 UAC 或 Elevation 使用频率的 SQL 查询?
- performance - 在页面边界访问数据时速度变慢?
- c# - Net Core:在返回 Html 的自定义标签助手中使用标签助手?
- sql - SQL Server:可选参数行为逻辑
- python - 使用 int 和 None 将字符串转换为数组
- python - 带有 :not 的 CSS 选择器未按预期运行