【问题标题】:How to access child component's value in other child component in angular 2如何在 Angular 2 中访问其他子组件中的子组件值
【发布时间】:2017-10-09 22:27:53
【问题描述】:

我有一个 Angular 2 项目设置,其中有一个名为 'app component' 的父组件,在 ap 组件中有 2 个名为 'child1 component' 和 'child2 component' 的子组件。

我的项目结构如下:

app.component
   -- child1 component
   -- child2 component

现在我的问题是:“child1 组件”中有一个按钮,“child2 组件”中有一个变量“variableOfChild2Component”。现在,当我单击“child1 组件”的那个按钮时,child2 组件的变量值应该会改变。如何在角度 2 中实现此要求?

【问题讨论】:

    标签: angular2-routing angular2-template angular2-directives


    【解决方案1】:

    对于组件交互,求助于服务,我只想为服务使用一个简单的名称,但使用对您的用例有意义的东西。

    import { Subject } from 'rxjs';
    
    @Injectable()
    export class MyService {
      private dataMessenger = new Subject<any>();
    
      getData(): Subject<any> {
        return this.dataMessenger;
      }
    
      setData(newData: any) {
        this.dataMessenger.next(newData);
      }
    }
    

    现在在您的组件 1 中使用按钮

    .
    .
    .
    export class Component1 ... {
      constructor(private myService: MyService) { }
    
      buttonClick() {
        this.myService.setData("Pass anything you want here");
      }
    }
    

    现在在您的组件 2 类中

    .
    .
    .
    export class Component2 ... {
      variableOfChild2Component: any;
    
      constructor(private myService: MyService) { }
    
      ngOnInit() {
        this.myService.getData()
                      .subscribe(data => {
                        // data argument contains whatever you pass to MyService.setData() 
                        // function inside your Component1 class when the button is clicked
                        this.variableOfChild2Component = data;
                      });
      }
    }
    

    您需要在您的模块中注册MyService,例如AppModule

    @NgModule({
      .
      .
      .
      providers: [ ..., MyService, ... ]
    })
    export class AppModule { }
    

    【讨论】:

    • 但是当我刷新 Component2 时,它不会进入订阅。我想当我刷新component2时,订阅后数据应该在那里。
    • 然后你将它保存在某个地方并在你认为合适的时候检索它,添加一个不同的问题
    • 这个问题应该怎么解决???因为我试图在另一个组件中创建一个静态属性并将数据传递给它,但是当我刷新浏览器时,该属性未定义。
    猜你喜欢
    • 2018-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-10
    • 1970-01-01
    • 2017-11-03
    • 2017-11-12
    • 1970-01-01
    相关资源
    最近更新 更多