【问题标题】:Angular2 refresh page after passing object to component将对象传递给组件后Angular2刷新页面
【发布时间】:2017-02-23 11:55:04
【问题描述】:

我正在尝试刷新页面以在另一个组件的模板中显示表格中的选定值,但没有成功,以下代码是一些组合代码,希望可以使问题变得清晰。 所以我有 2 个组件:
显示英雄列表的 TableComponent。
显示所选英雄详细信息的屏幕,这是 TableComponent 的子组件
目标是,当您从表格中单击英雄的名字时,详细信息将显示在“屏幕”组件中。所以代码:

 @Component({
  selector: 'heroes-table',
})
export class TableComponent implements OnInit {
  private tableData: Array<Object>; 
  //The component that will display the hero's details
  private screen: Screen;

  ngOnInit() {
    this.tableData = ['Windstorm', 'Bombasto', 'Magneta', 'Tornado'];
    this.screen = new Screen();
  }

//Function called when a hero is selected from the table view
public onSelect(hero: Object){
  this.screen.setHero(hero);
 }
}

表: //英雄表:

<div class="table-row-group" *ngFor="let hero of tableData" [class.selected]="hero === selectedHero" (click)="onSelect(hero)"> 
    <div class="table-row" >
      <div class="table-cell">{{hero}}</div>
    </div>
   //Screen is a child
  <screen></screen>
</div>

屏幕:

@Component({
  selector: 'screen',
})
export class Screen {

  private hero: Object;

  constructor() { }

  public setHero(hero: Object){
    this.incident=incident;
    console.log(this.hero)
  }
}

屏幕的模板:

//screen table:
<p>
  Current hero:{{hero}}
</p>

所以当我在控制台中调试时,我看到所选英雄打印在屏幕的setHero 方法中,但屏幕的视图不会刷新,它仍然是 : Selected her: 不显示任何内容。 有什么建议吗?

【问题讨论】:

  • 你可以使用@input装饰器来完成它。

标签: angular


【解决方案1】:

你可以使用 @input 装饰器来完成它。

@input 接收从父组件到子组件的数据

发送数据使用,

&lt;screen [hero]="hero"&gt;&lt;/screen&gt;

接收数据使用,

@Input() hero;

使用数据,

Current hero:{{hero}}

父组件:

@Component({
  selector: 'heroes-table',
})
export class TableComponent implements OnInit {
  private tableData: Array<Object>; 
  private screen: Screen;

  ngOnInit() {
    this.tableData = ['Windstorm', 'Bombasto', 'Magneta', 'Tornado'];
  }

public onSelect(hero: Object){
  this.hero = hero;
 }
} 

父 HTML:

<div class="table-row-group" *ngFor="let hero of tableData" [class.selected]="hero === selectedHero" (click)="onSelect(hero)"> 
        <div class="table-row" >
          <div class="table-cell">{{hero}}</div>
        </div>
       //Screen is a child
      <screen [hero]="hero"></screen>
</div>

观察&lt;screen [hero]="hero"&gt;&lt;/screen&gt;

子组件:

import { Component, Input } from '@angular/core';

@Component({
  selector: 'screen',
})
export class Screen {
  @Input() hero;
  constructor() {}
}

子视图:

<p>
  Current hero:{{hero}}
</p>

【讨论】:

    猜你喜欢
    • 2018-07-15
    • 1970-01-01
    • 2018-07-11
    • 2021-01-29
    • 2023-03-26
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 2016-05-10
    相关资源
    最近更新 更多