简体   繁体   English

Angular - 无法使用集合和 *ngFor 填充 mat-chip-list - 更新:设置 mat-select multiple 的值有问题吗?

[英]Angular - Cannot populate mat-chip-list with collection and *ngFor - Updated: Set value of mat-select multiple is problem?

I am having a problem populating a mat-chip-list .我在填充mat-chip-list时遇到问题。 In my angular component which is contained within a modal window I pass data using MAT_DIALOG_DATA .在包含在模态窗口中的角度组件中,我使用MAT_DIALOG_DATA传递数据。 This looks like so:这看起来像这样:

{
  name: 'string',
  email: 'string',
  tags: {
    company: [{displayName: 'string', id: ''}, ...] // can contain many or no items
  }
} 

I pass this through to the component and assign the companies property to a FormControl when I create the FormGroup for the component (see code below).当我为组件创建FormGroup时,我将其传递给组件并将公司属性分配给FormControl (请参阅下面的代码)。 I then use a method to return the FormControl value so I can loop through the content to produce a mat-chip-list , here is my template code:然后我使用一种方法返回FormControl值,以便我可以遍历内容以生成mat-chip-list ,这是我的模板代码:

<mat-select formControlName="companies" multiple class="edit-user__form__chip-select">
  <mat-select-trigger>
    <mat-chip-list>
      <mat-chip *ngFor="let company of outputChips('companies')"
                [removable]="true"
                (removed)="onChipRemove('companies', company)">
        {{ company.displayName }}
        <mat-icon matChipRemove>cancel</mat-icon>
      </mat-chip>
    </mat-chip-list>
  </mat-select-trigger>
  <mat-option *ngFor="let company of companyList" [value]="company">{{company.displayName}}</mat-option>
</mat-select>

here is my code file (i have only included the relevant parts):这是我的代码文件(我只包含了相关部分):

constructor(public dialogRef: MatDialogRef<EditAccountComponent>,
              @Inject(MAT_DIALOG_DATA) private data,
              private apiService: ApiService,
              private emailUniqueValidator: EmailUniqueValidator) {
    this.user = data;
  }

ngOnInit(): void {
    this.editAccountForm = this.createEditUserForm();
    // this returns a collection [{}, {}] where the objects have the same structure / signature
    // as the items contained with in the this.user.tags.company collection
    this.loadCompanies(); 
  }

createEditUserForm(): FormGroup {
    return new FormGroup({
      name: new FormControl(this.user.name, [Validators.required, Validators.max(50)]),
      email: new FormControl(
        this.user.emailAddress,
        [Validators.required, Validators.pattern('^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$')],
        this.emailUniqueValidator.validate.bind(this)
      ),
      companies: new FormControl(this.user.tags.company),
      roles: new FormArray([])
    });
  }

outputChips(control): any {
    return this.editAccountForm.controls[control].value;
  }

loadCompanies(): void {
    this.apiService.getTags('company', '').subscribe(tags => this.companyList = tags.slice(0, 20));
  }

Now my problem is that the mat-chip-list isn't being populated, however if I use the same code ( *ngFor ) with a <div> it will output the correct data.现在我的问题是mat-chip-list没有被填充,但是如果我使用相同的代码 ( *ngFor ) 和<div>它将输出正确的数据。 I am sure it maybe because I am using a FormControl to define the companies property/control of the FormGroup .我确定这可能是因为我使用FormControl来定义FormGroup的公司属性/控件。 So I changed this to a FormArray and formatted the this.user.tags.company to a FormArray like so...所以我将其更改为FormArray并将FormArray格式化为 FormArray 像这样......

createEditUserForm(): FormGroup {
    let formComps: FormArray;

    if (this.user.tags && this.user.tags.company) {
      formComps = new FormArray([...this.user.tags.company.map(item => new FormControl(item))]);
    }

    return new FormGroup({
      name: new FormControl(this.user.name, [Validators.required, Validators.max(50)]),
      email: new FormControl(
        this.user.emailAddress,
        [Validators.required, Validators.pattern('^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$')],
        this.emailUniqueValidator.validate.bind(this)
      ),
      companies: new FormArray(formComps),
      roles: new FormArray([])
    });
  }

However this produces an error "EditAccountComponent.html:38 ERROR TypeError: Cannot read property 'controls' of undefined" so when I use FormArray I can't bind to the template.但是,这会产生错误“EditAccountComponent.html:38 ERROR TypeError: Cannot read property 'controls' of undefined”,因此当我使用 FormArray 时,我无法绑定到模板。 I really am having trouble trying to determine what I should do to make this work.我真的很难确定我应该做什么来完成这项工作。 I am currently looking through Stackoverflow for answers but if anyone can explain where I am going wrong and what I should do to fix my problem I would be most appreciative.我目前正在通过 Stackoverflow 寻找答案,但如果有人能解释我哪里出错了以及我应该怎么做来解决我的问题,我将不胜感激。 If I have worded this question badly please comment and I shall rewrite and clarify.如果我对这个问题的措辞不好,请发表评论,我将重写和澄清。

** Update ** ** 更新 **

I'm starting to think that the problem isn't the mat-chip-list but the fact that the companies: new FormControl(this.user.tags.company) may not be correctly initialised, for example could this be a problem with setting the value or a mat-select with multiple values using a formControlName and not ngModal ?我开始认为问题不是 mat-chip-list 而是公司的事实companies: new FormControl(this.user.tags.company)可能没有正确初始化,例如这可能是一个问题使用formControlName而不是ngModal设置值或具有多个值的 mat-select ?

If you want to iterate over form array within your HTML you first need to specify formArrayName and then iterate over all of the controls.如果您想遍历 HTML 中的表单数组,您首先需要指定formArrayName ,然后遍历所有控件。 In your case, it should look more or less like that.在你的情况下,它应该或多或少看起来像这样。

<mat-select formArrayName="companies" multiple class="edit-user__form__chip-select">
  <mat-select-trigger>
    <mat-chip-list>
      <mat-chip *ngFor="let company of companies.controls"
                [removable]="true"
                (removed)="onChipRemove('companies', company)">
        {{ company.displayName }}
        <mat-icon matChipRemove>cancel</mat-icon>
      </mat-chip>
    </mat-chip-list>
  </mat-select-trigger>
  <mat-option *ngFor="let company of companyList" [value]="company">{{company.displayName}}</mat-option>
</mat-select>

But I am not sure if your error doesn't point some other problem.但我不确定您的错误是否指向其他问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 angular 材料 mat-select with mat-chip-list 通过 ENTER 而不是 DELETE 或 BACKSPACE 删除芯片 - angular material mat-select with mat-chip-list remove chip by ENTER instead of DELETE or BACKSPACE Angular 材料可重复使用 mat-chip-list 与 mat-autocomplete - Angular material reusable mat-chip-list with mat-autocomplete Angular Material 6 Mat-Chip-List-两个Mat-chip-list声明共享同一数据源 - Angular Material 6 Mat-Chip-List - two mat-chip-list declarations share the same data source Angular 5 - 在 mat-select 中使用对象填充选项? 不使用 NgFor? - Angular 5 - Populate Options In mat-select With Objects? Not With NgFor? 垫芯片列表中的角材料ngFor-如何防止断线? - Angular Material ngFor in mat-chip-list - how to prevent from line-break? 如何将初始值设置为 Angular Material mat-select multiple - How to set initial value to Angular Material mat-select multiple 如何在角度4中将值设置为多个垫选择 - How to set value to multiple mat-select in angular 4 Angular 2+ material mat-chip-list formArray 验证 - Angular 2+ material mat-chip-list formArray validation Angular mat-chip-list 带文本区怎么用? - How to use Angular mat-chip-list with text area? 输入未显示验证错误的角形材料垫芯片列表 - Angular material mat-chip-list with input not showing validation error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM