Angular:页面和组件之间的数据绑定在 ionic 4 中不起作用
Angular: Data Binding between a page and component nor working in 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 中,消息变量在绑定 "kicks in" 之前是未定义的。因此,当 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
的实际变量
我无法使用数据绑定将数据从页面传递到组件。
当我试图在构造函数中记录值时,它说它是未定义的。 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 中,消息变量在绑定 "kicks in" 之前是未定义的。因此,当 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
的实际变量