Program Tip

각도 재질 : 매트 선택 기본값을 선택하지 않음

programtip 2020. 10. 20. 08:02
반응형

각도 재질 : 매트 선택 기본값을 선택하지 않음


옵션이 배열에 정의 된 모든 객체 인 매트 선택이 있습니다. 옵션 중 하나를 기본값으로 설정하려고하지만 페이지가 렌더링 될 때 선택된 상태로 남아 있습니다.

내 typescript 파일에는 다음이 포함됩니다.

  public options2 = [
    {"id": 1, "name": "a"},
    {"id": 2, "name": "b"}
  ]
  public selected2 = this.options2[1].id;

내 HTML 파일에는 다음이 포함됩니다.

  <div>
    <mat-select
        [(value)]="selected2">
      <mat-option
          *ngFor="let option of options2"
          value="{{ option.id }}">
        {{ option.name }}
      </mat-option>
    </mat-select>
  </div>

내가 설정을 시도 selected2하고을 valuemat-option목적과의 ID 모두, 모두 사용하여 시도 [(value)][(ngModel)]mat-select, 그러나 아무도가 작동하지 않습니다.

재료 버전 2.0.0-beta.10을 사용하고 있습니다.


템플릿의 값에 바인딩을 사용합니다.

value="{{ option.id }}"

해야한다

[value]="option.id"

그리고 선택한 값 ngModel에서 value.

<mat-select [(value)]="selected2">

해야한다

<mat-select [(ngModel)]="selected2">

완전한 코드 :

<div>
  <mat-select [(ngModel)]="selected2">
    <mat-option *ngFor="let option of options2" [value]="option.id">{{ option.name }}</mat-option>
  </mat-select>
</div>

등의 측면에서 주 버전 2.0.0-beta.12 재료 선택 지금 받아들이 mat-form-field는 다른 재료 입력 컨트롤과 일치되도록 부모 요소로서 요소. 업그레이드 후 div요소를 mat-form-field요소로 대체하십시오 .

<mat-form-field>
  <mat-select [(ngModel)]="selected2">
    <mat-option *ngFor="let option of options2" [value]="option.id">{{ option.name }}</mat-option>
  </mat-select>
</mat-form-field>

사용 compareWith, 함수는 선택된 값으로 옵션 값을 비교합니다. 여기를 참조하십시오 : https://material.angular.io/components/select/api#MatSelect

다음 구조의 객체 :

listOfObjs = [{ name: 'john', id: '1'}, { name: 'jimmy', id: '2'},...]

다음과 같이 마크 업을 정의하십시오.

<mat-form-field>
  <mat-select
    [compareWith]="compareObjects"
    [(ngModel)]="obj">
       <mat-option  *ngFor="let obj of listOfObjs" [value]="obj">
          {{ obj.name }}
       </mat-option>
    </mat-select>
</mat-form-field>

그리고 다음과 같이 비교 함수를 정의하십시오.

compareObjects(o1: any, o2: any): boolean {
  return o1.name === o2.name && o1.id === o2.id;
}

저는 Angular 5와 반응 형을 mat-select와 함께 사용하고 있으며 위의 솔루션 중 하나를 사용하여 초기 값을 표시 할 수 없습니다.

mat-select 구성 요소 내에서 사용되는 다른 유형을 처리하기 위해 [compareWith]를 추가해야했습니다. 내부적으로 mat-select는 선택된 값을 보유하기 위해 배열을 사용합니다. 이 모드가 켜져있는 경우 동일한 코드가 여러 선택 항목과 함께 작동 할 수 있습니다.

각도 선택 제어 문서

내 해결책은 다음과 같습니다.

양식 제어를 초기화하는 양식 작성기 :

this.formGroup = this.fb.group({
    country: new FormControl([ this.myRecord.country.id ] ),
    ...
});

그런 다음 구성 요소에서 compareWith 함수를 구현하십시오.

compareIds(id1: any, id2: any): boolean {
    const a1 = determineId(id1);
    const a2 = determineId(id2);
    return a1 === a2;
}

다음으로 determineId 함수를 만들고 내 보냅니다 (mat-select에서 사용할 수 있도록 독립형 함수를 만들어야 함).

export function determineId(id: any): string {
    if (id.constructor.name === 'array' && id.length > 0) {
       return '' + id[0];
    }
    return '' + id;
}

마지막으로 mat-select에 compareWith 속성을 추가하십시오.

<mat-form-field hintLabel="select one">
<mat-select placeholder="Country" formControlName="country" 
    [compareWith]="compareIds">

    <mat-option>None</mat-option>
    <mat-option *ngFor="let country of countries" [value]="country.id">
                        {{ country.name }}
    </mat-option>
</mat-select>
</mat-form-field>

당신은 그것을 바인딩해야 [value]에서 mat-option아래와 같이

<mat-select placeholder="Panel color" [(value)]="selected2">
  <mat-option *ngFor="let option of options2" [value]="option.id">
    {{ option.name }}
  </mat-option>
</mat-select>

라이브 데모


Angular 6에서 이미 언급했듯이 반응 형으로 ngModel을 사용하는 것은 더 이상 사용되지 않으며 Angular 7에서 제거되었으므로 다음과 같이 템플릿과 구성 요소를 수정했습니다.

템플릿 :

<mat-form-field>
    <mat-select [formControl]="filter" multiple 
                [compareWith]="compareFn">
        <mat-option *ngFor="let v of values" [value]="v">{{v.label}}</mat-option>
    </mat-select>
</mat-form-field>

구성 요소의 주요 부분 ( onChanges및 기타 세부 사항은 생략 됨) :

interface SelectItem {
    label: string;
    value: any;
}

export class FilterComponent implements OnInit {
    filter = new FormControl();

    @Input
    selected: SelectItem[] = [];

    @Input()
    values: SelectItem[] = [];

    constructor() { }

    ngOnInit() {
        this.filter.setValue(this.selected);
    }

    compareFn(v1: SelectItem, v2: SelectItem): boolean {
        return compareFn(v1, v2);
    }
}

function compareFn(v1: SelectItem, v2: SelectItem): boolean {
    return v1 && v2 ? v1.value === v2.value : v1 === v2;
}

위의 this.filter.setValue (this.selected)참고하십시오 ngOnInit.

Angular 6에서 작동하는 것 같습니다.


자신 만의 비교 기능을 간단히 구현할 수 있습니다.

[compareWith]="compareItems"

문서 도 참조하십시오 . 따라서 완전한 코드는 다음과 같습니다.

  <div>
    <mat-select
        [(value)]="selected2" [compareWith]="compareItems">
      <mat-option
          *ngFor="let option of options2"
          value="{{ option.id }}">
        {{ option.name }}
      </mat-option>
    </mat-select>
  </div>

그리고 Typescript 파일에서 :

  compareItems(i1, i2) {
    return i1 && i2 && i1.id===i2.id;
  }

내 솔루션은 약간 까다 롭고 간단합니다.

<div>
    <mat-select
        [placeholder]="selected2">
      <mat-option
          *ngFor="let option of options2"
          value="{{ option.id }}">
        {{ option.name }}
      </mat-option>
    </mat-select>
  </div>

방금 자리 표시자를 사용했습니다 . 재료 자리 표시 자의 기본 색상은입니다 light gray. 옵션이 선택된 것처럼 보이게하기 위해 다음과 같이 CSS를 조작했습니다.

::ng-deep .mat-select-placeholder {
    color: black;
}

나를위한 해결책은 다음과 같습니다.

<mat-form-field>
  <mat-select #monedaSelect  formControlName="monedaDebito" [attr.disabled]="isLoading" [placeholder]="monedaLabel | async ">
  <mat-option *ngFor="let moneda of monedasList" [value]="moneda.id">{{moneda.detalle}}</mat-option>
</mat-select>

TS :

@ViewChild('monedaSelect') public monedaSelect: MatSelect;
this.genericService.getOpciones().subscribe(res => {

  this.monedasList = res;
  this.monedaSelect._onChange(res[0].id);


});

개체 사용 : {id : number, detalle : string}


이 예제에서와 같이했습니다. mat-select의 값을 mat-options 중 하나의 값으로 설정하려고했습니다. 그러나 실패했습니다.

My mistake was to do [(value)]="someNumberVariable" to a numeric type variable while the ones in mat-options were strings. Even if they looked the same in the template it would not select that option.

Once I parsed the someNumberVariable to a string everything was totally fine.

So it seems you need to have the mat-select and the mat-option values not only be the same number (if you are presenting numbers) but also let them be of type string.


Try this!

this.selectedObjectList = [{id:1}, {id:2}, {id:3}]
this.allObjectList = [{id:1}, {id:2}, {id:3}, {id:4}, {id:5}]
let newList = this.allObjectList.filter(e => this.selectedObjectList.find(a => e.id == a.id))
this.selectedObjectList = newList

참고URL : https://stackoverflow.com/questions/47333171/angular-material-mat-select-not-selecting-default

반응형