Angular 拆分数据对象中的逗号分隔值

Angular split comma separated values in data object

有一个数组数据,其中列作为逗号分隔值,如

Firstname: name.
Lastname:lastname
Cities lived: ex,ex,CV

现在想用mat select居住的城市,如何实现?

一个 angular 多选需要一个数组,所以你需要一个数组变量

//create two functions transform and parse
transform(user:User)
{
    return {...user,
            cities:user.cities?user.cities.join(','):null
    }
}
parse(userData:any)
{
    return {...userData,
            cities:userData.cities?userData.split(','):null
    }
}
//then you has two variables
user={firstName:..,lastName:..,cities:"ex,ex,CV"}
userData=this.transform(user)
//your "model" is userData, when you can obtain a real user you can do
this.user=this.parse(this.userData)

其他选项是制作自定义表单控件,例如 stackblitz

@Component({
  selector: 'multiselect-to-string',
  template: `
  <mat-form-field>

  <mat-select [placeholder]="placeHolder" [formControl]="control" multiple>
    <ng-container *ngIf="!key || !text">
    <mat-option *ngFor="let item of sourceList" [value]="item">
         {{item}}
    </mat-option>
    </ng-container>
    <ng-container *ngIf="key && text">
    <mat-option *ngFor="let item of sourceList" [value]="item[key]">
        {{item[text]}}
    </mat-option>
    </ng-container>
  </mat-select>
  </mat-form-field>

  `,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => MultiSelectToStringComponent),
      multi: true
    }]
})
export class MultiSelectToStringComponent implements ControlValueAccessor,OnInit,OnDestroy {
  @Input('placeholder')placeHolder;
  @Input('source')sourceList;
  @Input()key;
  @Input()text;

  onChange;
  onTouched;
  control=new FormControl();
  private alive:boolean=true;

  ngOnInit()
  {
     this.control.valueChanges.pipe(takeWhile(() => this.alive)).subscribe(value=>{
       if (this.onChange)
        this.onChange(value?value.join(','):null)
     })
  }
  ngOnDestroy()
  {
    this.alive=false;
  }
  writeValue(value: any[]|any): void {
    this.control.setValue(value?value.split(','):null);
  }

  registerOnChange(fn: any): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }

}

验证所有的答案,终于有了这个。

组件级别 考虑到 Array 中已有的数据,Mat select 需要 Array.

citydata = this.data.Cities.split(',')

HTML

<mat-select [placeholder]="placeHolder" [formControl]="control" multiple>
<mat-option *ngFor="let item of citydata" [value]="item">{{item}}
    </mat-option>

  </mat-select>