当鼠标悬停在<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>,我该怎么做?
发布于 2019-02-11 14:31:31
参考我的答案摘自正式文件。通过这个链接会有帮助。
可能会有不同的情况。让我们看看他们。
场景1:DetailComponent是当前组件的子组件
正如@nguyen在他的回答中所描述的,因为您在@input中定义了DetailComponent装饰器,如果DetailComponent是当前组件的子组件,而DetailComponent的选择器是app-detail,那么在html模板中,您将调用detail组件并传递值。
<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是兄弟关系,那么它们都将导入此服务,并使用与模型相同的变量,该模型将由组件更新或显示。
发布于 2019-02-11 14:04:42
假设DetailComponent是用选择器app-detail定义的
您需要将输入中的id分配给它
<app-detail [id]="assignedId"></app-detail>在包含详细组件的组件中,需要将值赋值给assignedId (或您命名的值)。
public assignedId;
public findId(id:number) {
this.assignedId = id;
}希望能帮上忙
https://stackoverflow.com/questions/54632203
复制相似问题