angular2:在组件之间传递属性

时间:2017-02-25 15:19:25

标签: angular typescript

我正在练习angular2(使用离子框架),我在组件之间传递数据时遇到了困难。

这是app.component.ts

@Component({
  template: `
    <ion-header>
      <ion-toolbar>
        <button ion-button icon-only menuToggle>
          <ion-icon name="menu"></ion-icon>
        </button>
        <ion-title>MyApp</ion-title>
      </ion-toolbar>
    </ion-header>

    <user-menu></user-menu>
    <ion-content padding>
      <h1>Active User: {{ activeUser }}</h1>
    </ion-content>
  `
})
export class MyApp {
  rootPage = TablePage;

  constructor(platform: Platform) {
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      StatusBar.styleDefault();
      Splashscreen.hide();
    });
  }
} 

这是user-menu.component.ts

@Component({
  selector: 'user-menu',
  template: `
    <ion-menu [content]="userMenu">
      <ion-content>
        <ion-row>
          <ion-list>
            <ion-list-header>
              Users
            </ion-list-header>
            <ion-item *ngFor="let user of users;" menuClose [class.selected]="user === activeUser" (tap)="onSelect(user)">
              {{ user.name }}
            </ion-item>
          </ion-list>
        </ion-row>
      </ion-content>
    </ion-menu>

    <ion-nav #userMenu [root]="rootPage"></ion-nav>
  `,
  styles: [`
    .selected {
      background-color: #CFD8DC !important;
      color: white;
    }
  `],
  providers: [UserService]
})
export class UserMenuComponent {
  users: User[];
  activeUser: User;

  constructor(private userService: UserService) {}

  getUsers(): void {
    this.userService.getUsers().then(users => this.users = users);
  }

  ngOnInit(): void {
    this.getUsers();
  }

  onSelect(user: User): void {
    this.activeUser = user;
  }
}

如何在主要组件中获得activeUser?在下一步中,我想根据此用户显示相关数据,甚至可能将其传递给第三个组件。

感谢。

1 个答案:

答案 0 :(得分:2)

1)模板参考为你工作

<user-menu #menu></user-menu>

{{ menu.activeUser }}

另见

2)另一种方法是在UserMenuComponent

中使用@Output事件
export class UserMenuComponent {
  @Output() onSelected = new EventEmitter();

  onSelect(user: User): void {
    this.activeUser = user;
    this.onSelected.emit(user);
  }

并在父模板中使用它

<user-menu (onSelected)="activeUser = $event"></user-menu>

另见