【问题标题】:Send Variabel to another component in Angular将变量发送到 Angular 中的另一个组件
【发布时间】:2018-03-02 19:33:21
【问题描述】:

我想将一个变量发送到另一个组件。

组件A中的HTML-doc,我想将user.id发送到组件B

<li class="list-group-item list-group-item-action" *ngFor="let user of users">
 <a routerLink="/profile"  routerLinkActive="active" (click)="testFunc(user.id)">
  {{user.name}}
 </a>
</li>

我想将 id 发送到组件 B 的组件 A(这是我卡住的地方)

 testFunc (id: JSON): string {
    //Send to component B
  }

我不知道这是否足够信息,但如果需要,我可以提供更多信息。

【问题讨论】:

  • 您可以使用该线程stackoverflow.com/questions/33338276/angular-2-event-broadcast中描述的广播事件@
  • 组件 A 和 B 如何相关(父子、兄弟或完全不相关)?它们出现在您的应用中的什么位置?
  • 应该是父子但我认为它无关的atm
  • 这确实取决于组件之间的关系,能否请您展示您的模板以显示两个组件或至少概述一下它的外观?

标签: html angular typescript components


【解决方案1】:

如果我理解你的代码,当你点击你去 /profile 页面的链接。 因此,如果内容 B 是配置文件组件,您可以发送您的 user.id 抛出路由器参数,如:

<a [routerLink]="['/profile', user.id]">

当然之前配置正确的路由。您可以查看以下文档:

在 app.module.ts 中

const appRoutes: Routes = [ 
  {path: 'addProfile', component: AddProfileComponent }, 
  {path: 'listProfiles', component: ListProfilesComponent}, 
  {path: 'profile/:id', component: ProfileComponent}
]

在 ProfileComponent 中

export class ProfileComponent implements OnInit {
     private selectedId: number;

     constructor(private route: ActivatedRoute) {}

     ngOnInit() {
       this.route.paramMap
                 .switchMap(params => this.selectedId = +params.get('id');
       // second option
       this.route.params.subscribe(params => this.selectedId = +params['id'])
    }
}

如果您单击链接时只想向页面中的组件发送值,则可以使用 @Input 装饰器。像这样:

<componentA>
    <li class="list-group-item list-group-item-action" 
        *ngFor="let user of users">

        <a routerLink="/profile"  routerLinkActive="active"
           (click)="testFunc(user.id)">{{user.name}}</a>
    </li>

    <componentB [inputName]="userId"></componentB>
</componentA>

在 ts 文件中:

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

@Component({
  selector: 'componentA',
  templateUrl: 'url'
})
export class ComponentA {
  public userId: string = ""
  constructor() {}

  public function testFunc(id: string): void {
     this.userId = id
  }
}

....

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

@Component({
  selector: 'componentB',
  templateUrl: 'url'
})
export class ComponentB implements OnInit {
  @Input() inputName: string;
  constructor() {}

  function ngOnInit(): void {
     console.log(inputName)
  }
}

小心,不要尝试将输入变量显示到不起作用的构造函数中

【讨论】:

  • 第一个答案就是我要找的,但是组件将如何获取 id?通过构造函数?
  • 因为这是我的路线在app.module.tsconst appRoutes: Routes = [ { path: 'addProfile', component: AddProfileComponent }, { path: 'listProfiles', component: ListProfilesComponent}, { path: 'profile', component: ProfileComponent} ];中的样子
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-01-16
  • 1970-01-01
  • 2020-12-06
  • 1970-01-01
  • 2018-07-19
  • 2013-09-16
  • 1970-01-01
相关资源
最近更新 更多