【问题标题】:Multiple shared cascading combobox component in angular 7Angular 7中的多个共享级联组合框组件
【发布时间】:2019-01-03 10:33:17
【问题描述】:

我创建了一个用于管理级联国家和州的组件。如果我只组建一个国家和一个州,那么一切都会完美无缺。但是,当我输入三个国家和州时,一切都会像下面的例子一样被破坏。我怎样才能做到这一点?

一个国家/地区(工作示例)

Stackblitz

三个国家/地区(非工作示例)

Stackblitz

【问题讨论】:

  • 你有一个独特的元素,你在找FormArray吗? angular.io/guide/…
  • 我的主要问题是级联组合框。当我选择第一个country,第一个和第二个state,填充。但我只想先填写state@Eliseo。
  • 您能否更具体地说明您的问题?我看不出你实际上遇到了什么问题。你具体希望发生什么?你想做什么?
  • 所以您需要一个可以让您拥有多个单独国家/州值的表单?如果是这样,具体是只有两个国家/州选项,还是有可能有人提交说......三个?
  • 好的,所以我们需要在这里变得非常具体。一个人可以拥有多个国家/州吗?还是每人一个国家/州?

标签: angular typescript angular7


【解决方案1】:

您有两个引用相同变量的元素:

<app-country [studentForm]="studentForm"></app-country>
<app-state [studentForm]="studentForm"></app-state>

<br/><br/>

<app-country [studentForm]="studentForm"></app-country>
<app-state [studentForm]="studentForm"></app-state> 

每个组件都可以访问 studentForm 类的相同属性。如果您希望单独填充该组件组,则必须编写如下内容:

app.component.ts:

 this.studentForm = new FormGroup({
  'studentName':new FormControl(''),
  'countryId1': new FormControl(''),
  'stateId1': new FormControl(''),
  'countryId2': new FormControl(''),
  'stateId2': new FormControl('')
})

app.component.html:

<app-country [studentForm]="studentForm" [id]="'countryId1'"></app-country>
<app-state [studentForm]="studentForm" [id]="'stateId1'" [countryId]="'countryId1'"></app-state>

<br/><br/>

<app-country [studentForm]="studentForm" [id]="'countryId2'"></app-country>
<app-state [studentForm]="studentForm" [id]="'stateId2'" [countryId]="'countryId2'"></app-state>

并且在你的国家和州组件中分别使用countryId1/countryId2和stateId1/stateId2(还需要修改国家和州组件使用'id'参数)。

更新

在 country.component.ts 添加

@Input() id: string;

在 state.component.ts 中添加

@Input() id:string;
@Input() countryId:string;

get states(): State[]{
   var val = this.studentForm.controls[this.countryId].value;
   return this.selectService.filterStates(val);
};

在 country/state.component.html 中更改为:

<select [formControlName]="id">...

在 select.service.ts 中更改:

filterStates(countryId){
   if(!countryId) return null;
   return this.getStates().filter((item) => item.countryid == countryId);
}

【讨论】:

  • 谢谢@RomaRuzich。但是如何使用 for 'id' 参数修改我的组件?因为,我是 Angular 的新手。
  • 阅读angular.io/guide/component-interaction,了解如何在组件之间发送数据。因此,在子组件(国家/州组件)中,您采用字符串类型的参数“id”。然后在 country/state.component.html 你在 'formControlName' 传递 'id' 参数的值。
  • 有文章medium.com/@mail.bahurudeen/…。它必须帮助你。
  • 再次感谢@RomaRuzich。但这些都是非常大的文件。很难知道使用什么以及如何使用。
  • 我编辑了答案。但我会用另一种方式做到这一点。我会为国家/地区组件创建组件包装器,并在 app.component 中使用它。
猜你喜欢
  • 2019-03-31
  • 2011-03-23
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 2020-03-14
  • 2021-12-05
相关资源
最近更新 更多