【问题标题】:Angular 2 tabset - Tabs talking to eachotherAngular 2 tabset - 标签相互交谈
【发布时间】:2016-09-14 05:51:48
【问题描述】:

目前在我的项目中,我有一个 angular2 选项卡集,可以显示其他 html 模板,如下所示 -

Tabs.html

<tabset class="Myclass">
  <tab heading ="Page1" (select)="sendMessageToPage2(Message)"<PageOne id="0"></PageOne></tab>
  <tab heading ="Page2" (select)="sendMessageToPage1(Message)"<PageTwo></PageTwo></tab>
</tabset>

Tabs.ts

import {PageOneComponent} from 'filespace.PageOne';
import {PageTwoComponent} from 'filespace.PageTwo';
import { TAB_DIRECTIVES } from 'ng2-bootstrap/ng2-bootstrap';

@Component({
  moduleId: module.id,
  selector: 'tabs',
  templateUrl: 'tabs.html',
  directives: [PageOneComponent, PageTwoComponent, TAB_DIRECTIVES] })

export class tabs {

public sendMessageToPage1(message: string){ do Stuff }
public sendMessageToPage2(message: string){ do Stuff }
}

我的问题是我如何真正从第 1 页到第 2 页获取我的消息,或者让他们共享一个变量。基本上我需要第 1 页来对第 2 页上发生的更改做出反应,或者在返回到第 1 页时运行某些功能。

【问题讨论】:

    标签: javascript html angular typescript


    【解决方案1】:

    您需要从 PageOnetabs 组件发出事件,然后从标签控制其他组件:

    @Component({
      selector: 'PageOne',
      templateUrl: `<div (click)="onClick()">Click Me</div>`
    })
    
    export class PageOne {
        // creating EventEmitter to emit when onClick is called
        @Output() changed = new EventEmitter();
        onClick() {
            this.changed.emit();
        }
    }
    

    或者更好的方法是在这两个组件(PageOne 和 PageTwo)之间共享一个服务并通过服务进行通信,总之tabs 模块tabs.module 中提供了一个服务。 ts|jsPageOnePageTwo 作为标签模块的组件可以访问它(Angular2 中的 DI),然后它们通过该服务进行通信,它们可以publich/subscribe消息,更多信息请参考

    https://angular.io/docs/ts/latest/tutorial/toh-pt4.html http://blog.thoughtram.io/angular/2015/09/17/resolve-service-dependencies-in-angular-2.html

    对于publih/subscribe,您可以参考: https://coryrylan.com/blog/angular-2-observable-data-services

    【讨论】:

    • 感谢就像一个魅力。两者都使用相同的服务,并使用它来填充他们的视图。
    猜你喜欢
    • 1970-01-01
    • 2010-09-09
    • 2011-06-02
    • 2013-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多