[英]how to pass dynamic data from parent to child in angular2+
As we know, in angular parent to child communication happened using @Input decorator but how to pass dynamic data from parent to child.for example 'name' property is defined in parent and it's value changes dynamically and updated value of 'name' we are going to using in child component so how to achieve it without services.正如我们所知,在 angular 中,父子通信使用 @Input 装饰器发生,但如何将动态数据从父子传递给子。例如,'name' 属性是在父级中定义的,它的值动态变化并更新了 'name' 的值打算在子组件中使用,那么如何在没有服务的情况下实现它。
you can watch your input changes in the child component with ngOnChanges lifecycle您可以使用 ngOnChanges 生命周期查看子组件中的输入更改
in your child component you should implements OnChanges
在您的子组件中,您应该
implements OnChanges
ngOnChanges(changes: SimpleChanges): void {
for (let propName in changes) {
let change = changes[propName];
if (propName === "YOUR_INPUT_NAME") {
this.YOUR_INPUT_NAME = (change.currentValue);
}
}
}
You can make the use of service to get the updated value in child when it gets changed in parent.您可以使用服务在父项中更改时获取子项中的更新值。
For that you need to declare the variable in the service of type observable.为此,您需要在可观察类型的服务中声明变量。 your myService.service.ts would be having the following code:
您的myService.service.ts将具有以下代码:
@Injectable()
export class myService {
myInput:BehaviorSubject<boolean> = new BehaviorSubject(false)
}
now from your parent component change the value of this myInput by using:现在从您的父组件中使用以下方法更改此 myInput 的值:
myServie.myInput.next(true)
and subscribe this variable in your child component by using:并使用以下方法在您的子组件中订阅此变量:
myService.myInput.subscribe((data)=>{console.log(data)})
In both the parent and child component add the line private mySerivce:MyService
in the arguments of constructor.在父组件和子组件中,在构造函数的 arguments 中添加行
private mySerivce:MyService
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.