数据对象中的角分隔逗号分隔值

时间:2019-02-06 04:03:28

标签: angular angular-material angular-material-6

具有以列为逗号分隔值的数组数据,例如

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

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

2 个答案:

答案 0 :(得分:0)

角度多重选择需要一个数组,因此您需要一个数组变量

//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;
  }

}

答案 1 :(得分:0)

验证所有答案,最终找到答案。

组件级别 考虑到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>