简体   繁体   English

如何在angular2+中将动态数据从父级传递给子级

[英]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.

相关问题 如果子组件为动态组件,如何将数据从子组件传递给父组件 - How to pass data from Child to Parent, if Child component dynamic component 如何将数据从子级传递到父级:Angular2 - How to pass data from Child to Parent: Angular2 如何将数据从子组件传递到父组件 Angular - How to Pass data from child to parent component Angular 如何以角度将多个数据从子组件传递回父组件? - How to pass multiple data back from child to parent component in angular? 如何从Angular2的父级中的dataService接收的数据传递给子级 - How to pass data received from dataService in parent to child in Angular2 如何使用角度$ broadcast将数据从父级传递到子级控制器? - How to pass data from parent to child controller using angular $broadcast? Angular2+ 将存储中的数据显示到动态输入字段 - Angular2+ display data from storage onto dynamic input field 如何将数据从子 angular 应用程序传递给父非角度应用程序? - how to pass data from child angular application to parent non-angular application? 无法使用@ViewChild Angular 7将数据从子级传递到父级 - Can't pass data from Child to Parent using @ViewChild Angular 7 如何在 React 中将动态值从父级传递给子级? - How to pass a dynamic value from parent to child in React?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM