【问题标题】:Angular 2~6: What is the most efficient way to communicate with "Components"?Angular 2~6:与“组件”通信的最有效方式是什么?
【发布时间】:2018-12-10 13:43:55
【问题描述】:

目前我只知道这些方法:

  • @输入/@输出 |这是为了让孩子与父母交流,反之亦然
  • @ViewChild |这是为了和子组件通信
  • @Injectable 服务 |与任何组件共享数据
  • rxjs/behaviorsubject |与任何组件共享数据

我还看到了一个@Injectable 组件示例,但我不确定这是否也是共享组件数据的一种方式。

好的,所以我希望上面的文字足够清晰,以便大家能够理解我要去哪里。我需要最有效和最干净的方式来与任何组件共享组件变量和方法,而不必造成大混乱并看到性能下降。

我正在考虑使用以下方式共享数据,但我不确定这在拥有多个组件时是否有效:

家长

import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child/child.component';

@Component({
    selector: 'app-parent',
    templateUrl: './parent.component.html',
    styleUrls: ['./parent.component.scss']
})
class ParentComponent implements OnInit, AfterViewInit {
    public instance: ParentComponent;
    @ViewChild(ChildComponent) childComponent;

    constructor() {
        this.instance = this;
    }

    doSomethingWithParentMethod(strData: string) {
        console.log('parent data: ' + strData);
    }

    ngOnInit(): void {
    }

    ngAfterViewInit() {
        this.childComponent.doSomethingMethod('pass data to child in string type');
    }
}

在父 HTML 文件中:

<app-child [parent]="instance"></app-child>

孩子

@Component({
    selector: 'app-child',
    templateUrl: './child.component.html',
    styleUrls: ['./child.component.scss']
})
class ChildComponent {
    @Input() parent;

    public function doSomethingMethod(strData: string) {
        console.log('child data: ' + strData);
    }

}

【问题讨论】:

    标签: angular typescript components angular6 data-sharing


    【解决方案1】:
    @Injectable Service | share data with any component
    

    根据需求变化,但通用服务主要用于数据传输

    【讨论】:

    • 我想在单击父 html 按钮元素时使用来自其他组件的方法。我知道这可以通过 (click)="{{fireMethod()}}" 实现,但是在父方法内部,我希望能够触发子方法,反之亦然。
    猜你喜欢
    • 1970-01-01
    • 2018-05-24
    • 1970-01-01
    • 2010-12-06
    • 2017-03-28
    • 2010-09-06
    • 2017-02-19
    • 1970-01-01
    • 2019-09-09
    相关资源
    最近更新 更多