我正试图将数据从父传递给子。当我将字符串(data1(从父对象传递给子对象时,我会得到正确的输出,但当我尝试显示对象时,控制台会说它未识别,屏幕上什么也不显示。
父组件:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
data={
name:'Charles',
age:24,
email:'charles@gmail.com'
};
data1 = "Charles";
}
<app-contact [sendName] ="data"></app-contact>
子组件
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-contact',
templateUrl: './contact.component.html',
styleUrls: ['./contact.component.css']
})
export class ContactComponent implements OnInit {
@Input() sendName;
constructor() { }
ngOnInit(): void {
console.log(this.sendName);
}
}
<h1 class="text-center">Contact Form</h1>
<h3 class="pb-5">from the parent {{sendName.name}}</h3>
<h3 class="pb-5">from the parent {{sendName.age}}</h3>
请有人帮帮我。谢谢
如果data
(在父组件中(变量具有静态值,则子组件将是
@Input() sendName;
ngOnInit(): void {
console.log(this.sendName);
}
如果data
(在父组件中(变量将从动态值分配,则子组件将是
(假设您有一个API来调用和更新API响应上的sendName
变量,但我们的子组件在没有等待API响应的情况下被初始化,那么我们需要触发@Input()
来发送子组件中的更新数据(
@Input() set sendName(value: any) {
if(value){
console.log(value);
this.name = value
// call any function from here
}
}
name:any; // use this variable at anywhere
constructor(){
}
在设置父中的数据值之前,您可能正在渲染子
在子组件中导入Onchanges并从ngOnchanges((中获取
import { Component, OnInit, Input ,Onchanges} from '@angular/core';
export class ContactComponent implements OnInit,Onchanges {
@Input() sendName; constructor() { }
ngOnChanges() {
console.log(this.sendName); }