首页 > 解决方案 > 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>

标签: angularionic-frameworkdata-bindingionic4angular-components

解决方案


这是预期的行为。在您的 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 的实际变量


推荐阅读