angular - Angular:页面和组件之间的数据绑定,也不能在 ionic 4 中工作
问题描述
我无法使用数据绑定将数据从页面传递到组件。
当我试图在构造函数中记录值时,它说它是未定义的。message是用于实现数据绑定的变量的名称。
app-floating-text-white.ts ( 组件 )
import { Component, OnInit ,Input} from '@angular/core';
@Component({
selector: 'app-floating-text-white',
templateUrl: './floating-text-white.component.html',
styleUrls: ['./floating-text-white.component.scss'],
})
export class FloatingTextWhiteComponent implements OnInit {
@Input() message: string;
constructor() {
console.log(this.message)
}
ngOnInit() {}
}
app-floating-text-white.html ( 组件 )
<p> {{message}} </p>
page.html
<app-floating-text-white [message]="Hello World"> </app-floating-text-white>
解决方案
这是预期的行为。在您的 app-floating-text-white.ts 中,消息变量是未定义的,直到绑定“开始”。因此,当在构造函数中调用 console.log 时(在组件创建时发生),消息的值仍然未定义。
在最近的 CDR 周期中,绑定将被刷新,并且新值“Hello World”将被传递到您的子组件中。
尝试添加 ngAfterViewInit { console.log(this.message) } 并查看刷新所有绑定后会发生什么(检查并刷新所有绑定后触发 ngAfterViewInit)。
我还注意到您在这里使用单引号来绑定值:
<app-floating-text-white [message]="Hello World"> </app-floating-text-white>
上面的代码期望 Hello World 是一个变量。你需要把它变成一个字符串:
<app-floating-text-white [message]="’Hello World’"> </app-floating-text-white>
或绑定到 page.ts 的实际变量
推荐阅读
- python - 在数据框中查找两列的交集
- php - 最后一个值没有出现在动态 php 数组中
- android - AAR 依赖项 - 捆绑或不捆绑?
- reactjs - 子组件的道具类型
- c# - 无法使 C# HttpClient 在较长的 API 响应时间内可靠地工作
- google-apps-script - 如何将我处于开发模式的应用程序安装到同一域的另一个用户?
- excel - Excel VBA 缩短 If 语句代码以实现自动化
- sql - BigQuery - 来自 SQL Server 后台时如何考虑查询优化
- wordpress - Rest api 在从 Wordpress 调用时返回错误 403,但在邮递员中工作
- linux-kernel - 如何定制现有的内核模块以支持未来的升级和多种 Linux 风格?