如何从 html 传递一个值以供其他组件函数使用 Typescript

How to pass a value from html to be use from other component functions Typescript

我有一个下拉菜单,我想在其他组件函数中传递所选值的 Id ($event.target.value)。

 <div class="dropdown  ml-auto">
   <select  (change)=getSelectedVariantProject($event.target.value)>
      <option value = "default">Select project</option>
      <option *ngFor = "let project of selectProject" value = {{project.projectId}}>{{project.projectName}}</option>
   </select>
 </div>

我有这两个功能的项目服务:

getProjects(): Observable<any>{
    return this.http.get<Project>(this.urlProject)
    .pipe(
    catchError(this.handleError('getProject',[]))
  );
  }

  getProjectVariant(id: number): Observable<any>{
    var url = this.urlProjectVariant;
    url = url + id;
    return this.http.get<ProjectVariant>(url)
      .pipe(
        catchError(this.handleError('getProjectVariant',[]))
      )
  }

我有 table 组件,其中我需要参数 projectVariantId 中 HTML 的 id 值:

export class TablesComponent implements OnInit {

  filters: MisraLint;
  pageMisraMessages: PageMisraLintTable;
  selectedPage : number = 0;
  buildId: number = 1;
  sizeTableEntries: number = 100;
  page: any;

  constructor(private misraService: MisraService) { }

  getFilters(): void{  
    this.misraService.getMisraLintFilters(2)
      .subscribe(filters => this.filters = filters);
  }

  getPageMisra(page:number,projectVariantId: number,size:number,buildId:number): void{
    this.misraService.getPageMisraLint(page,projectVariantId, size,buildId)
      .subscribe(pageMisra => {
        this.pageMisraMessages = pageMisra
        console.log("Misra meessgaes: " + pageMisra.content)
      })

  }

  getMisraLintByFilters(page: number, projectVariantId: number, size:number, filter: string)
  {
       //call rest API to apply filters
   this.misraService.getMisraLintByFilters(page,projectVariantId,size,filter)
   .subscribe(pageMisra => {
     this.pageMisraMessages = pageMisra
   })
  }

  ngOnInit() {
    this.getFilters();
    this.getPageMisra(0,2,this.sizeTableEntries,this.buildId);
  }
}

我不知道该怎么做。如何传递 $event.target.value 因为当用户从下拉列表中选择某些内容时,我需要此值作为其他组件函数(在打字稿中)的参数。

您有:<select (change)=getSelectedVariantProject($event.target.value)>

您可以在组件端添加一个变量。比如 selectedvariant 什么的,或者直接在函数上使用它,比如:

getSelectedVariantProject(val){//code here} 注意 (val) 是你的 $event.target.value.

示例:

selectedvariant:any = val;

if(condition === condition_equal_to_whatevervalusage

阅读更多信息here

方法 1.) 如果您在同一页面上使用其他组件而不是

在component.ts

selectedProject = null;

getSelectedVariantProject(id){
 this.selectedProject = id;
}

在component.html

<app-other-component selectedProject="selectedProject"></app-other-component>

在otherComponent.ts

@Input() selectedProject;

方法 2.) 或者其他组件位于您无法使用服务的其他页面上。

在组件中

constructor(private someService: SomeService) {

}

getSelectedVariantProject(id){
     this.someService.selectedProject = id;
}

在otherComponent.ts

constructor(private someService: SomeService) {
 console.log(this.someService.selectedProject);
}