在Angular 6中以编程方式调用组件

时间:2019-02-11 13:59:36

标签: javascript angular typescript angular6

当我将鼠标悬停在<li>上以运行详细信息组件时,我想使用此功能。

  findId(id:number){
     console.log(id)
  }

此函数运行时必须向该组件发送ID:

export class DetailComponent implements OnInit {

    @Input() id:number;
    constructor() { }
   ngOnInit() {
   }
  }

这是HTML文件:

<ul>
  <li *ngFor="let cat of cats" >
    <a (mouseover)="findId(cat.id)">{{cat.name}}</a>
  </li>
</ul>

demo of my code

我该怎么做?

3 个答案:

答案 0 :(得分:1)

假定用选择器app-detail定义了DetailComponent

您需要将输入中的id分配给它

<app-detail [id]="assignedId"></app-detail>

,在包含详细信息组件的组件中,需要将值分配给assignedId(或任何您命名的名称)

public assignedId;

public findId(id:number) {
    this.assignedId = id;
}

希望获得帮助

答案 1 :(得分:1)

对我的回答的引用来自official documentation。通过此链接会有所帮助。

可能有不同的情况。让我们看看它们。

  • DetailComponent是您当前组件的子代
  • DetailComponent是您当前组件的兄弟
  • DetailComponent是您当前组件的父级

方案1 :DetailComponent是当前组件的子代

如@nguyen在回答中所述 由于您已在DetailComponent中定义了@input装饰器,因此如果DetailComponent是当前组件的子级,并且DetailComponent的选择器假设为app-detail,则在html模板中,您将调用详细说明组件并传递值

<app-detail[id]="selectedId"></app-detail>

提供的selectedId是当前组件的类变量,其中包含要传递给DetailComponent的ID

即假设您的功能

findId(id:number){
     console.log(id)
  }

正在工作,您可以在控制台中看到ID,然后修改功能

findId(id:number){
     console.log(id);
     this.selectedId = id;
  }

对于方案2 方案3 ,请查看文档,您可以选择使用事件发射器传递值。

否则,我想做的是创建一个服务,该服务保存多个组件共有的值。然后,将服务导入使用这些值的组件中。

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class DataStoreService {
  selectedId: string;
}

在当前组件中:

export class CurrentComponent implements OnInit {

    constructor(public dataStoreService: DataStoreService) { }
    ngOnInit() {}

    findId(id:number){
     this.dataStoreService.selectedId = id;
  }
  }

然后在您的DetailComponent中导入服务

export class DetailComponent implements OnInit {

    constructor(public dataStoreService: DataStoreService) { }
    ngOnInit() {}
  }

在您的DetailComponent html模板中

<div>{{dataStoreService.selectedId}}</div>

如果CurrentComponent和DetailComponent是同级,则它们都将导入此服务,并使用与模型相同的变量,该变量将由组件更新或显示。

答案 2 :(得分:-2)

要在鼠标悬停时调用函数,请添加@HostListener:

 @HostListener('mouseover')  
 findId(id:number){
      console.log(id)
   }

edit:是的,我想这是个愚蠢的建议,OP已经将他的代码挂在了mouseover上。特别是li ...;忽略