angular - 角度输入不产生结果。在父组件中
问题描述
父.html
<div>
<p>form the parent</p>
<app-child>[value]="from the parent"</app-child>
</div>
child.html
<p>child works!</p>
<h1>{{value}}</h1>
child.component.ts
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
@Input() value : string;
constructor() {
}
ngOnInit() {
console.log(this.value);
}
}
角度输入不产生结果。在父组件中。尽管我在子组件中使用了 value。
解决方案
这是因为您使用错误的语法将输入值传递给组件 - 您在组件标签内指定输入值,因此 Angular 会将其视为您尝试将 HTML 传递给组件的<ng-content>
. 相反,您应该像在 HTML 标记上指定属性一样指定它:
<div>
<p>form the parent</p>
<app-child [value]="from the parent"></app-child>
</div>
此外,您不应将value
属性括在方括号中,因为 Angular 会将其视为您的组件模板中有一个名为from the parent
. 但是由于您的组件中没有这样的属性,它可能无法正确呈现。相反,您应该将属性值括在单引号内或删除方括号:
<div>
<p>form the parent</p>
<app-child value="from the parent"></app-child>
</div>
或者:
<div>
<p>form the parent</p>
<app-child [value]="'from the parent'"></app-child>
</div>
有关更多信息,请查看Angular 模板语法文档的表达式上下文部分。
推荐阅读
- javascript - 如何通过鼠标滚轮水平滚动div,锁定正文滚动?
- asp.net-mvc - ASP.NET Core 3.0 控制器路由不起作用
- c++ - Qt - 为什么无法使用从 FileDialog 获取的目录使用 QFile 读取文件?
- design-patterns - 编程语言设计范式或信号和系统
- python - python选择解释列表索引重新分配的动机是什么?
- regex - 使用正则表达式替换长 URL 中的文本
- python - 使用终端下载后如何访问kaggle数据?
- c - 有一个致命的错误代码 - 损坏的堆
- java - 如何从 int 数组(Java)中删除空元素?
- javascript - 使用反应钩子加载效果