加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular 2 – 一个组件触发刷新页面上的另一个组件

发布时间:2020-12-17 08:51:19 所属栏目:安全 来源:网络整理
导读:我有一个组件ComponentA,显示元素列表.此列表在ngOnInit期间显示. 我有另一个组件ComponentB提供可能影响ComponentA中显示的元素列表的控件.例如.可以添加元素. 我需要一种方法来触发ComponentA的重新启动. 有人有想法吗? 细节 A是一个HeaderBar,其菜单显示
我有一个组件ComponentA,显示元素列表.此列表在ngOnInit期间显示.

我有另一个组件ComponentB提供可能影响ComponentA中显示的元素列表的控件.例如.可以添加元素.

我需要一种方法来触发ComponentA的重新启动.

有人有想法吗?

细节

A是一个HeaderBar,其菜单显示“savedSearchs”列表

@Component({
  selector: 'header-bar',templateUrl: 'app/headerBar/headerBar.html'
})
export class HeaderBarComponent implements OnInit{
  ...
  ngOnInit() {
    // init list of savedSearches
    ...
  }
}

B是一个可以保存搜索的SearchComponent

@Component({
  selector: 'search',templateUrl: 'app/search/search.html'
})
export class SearchComponent implements OnInit {
  ...
}
你需要提供组件,并将其注入组件的构造函数中,你需要像我一样调用其他组件的ngOnInit.

Plunker演示:https://plnkr.co/edit/M0d65wHjfg4KfwaQ5mPM?p=preview

//our root app component
import {Component,NgModule,VERSION,OnInit} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  selector: 'my-app',template: `
    <div>
      <h2>Hello {{name}}</h2>
       <comp-one></comp-one>
       <comp-two></comp-two>
    </div>
  `,})
export class App {
  name:string;
  constructor( ) {
    this.name = `Angular! v${VERSION.full}`
  }
}

// ComponentOne with ngOnInit

@Component({
  selector: 'comp-one',template: `<h2>ComponentOne</h2>`,})
export class ComponentOne implements OnInit {

  ngOnInit(): void {
    alert("ComponentOne ngOnInit Called")
  }

}

// Added provider of ComponentOne here and injected inside constructor the on button click call ngOnInit of ComponentOne from this component
@Component({
  providers:[ComponentOne],selector: 'comp-two',template: ` Component Two: <button (click)="callMe()">Call Init of ComponentOne</button>`,})
export class ComponentTwo implements OnInit {

   constructor(private comp: ComponentOne ) {
    this.name = `Angular! v${VERSION.full}`
  }
  public callMe(compName: any): void {
    this.comp.ngOnInit();
  }


}
@NgModule({
  imports: [ BrowserModule ],declarations: [ App,ComponentOne,ComponentTwo ],bootstrap: [ App ]
})
export class AppModule {}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读