Angular의 객체에 선택 요소 바인딩
선택 요소를 개체 목록에 바인딩하고 싶습니다. 이 작업은 매우 간단합니다.
@Component({
selector: 'myApp',
template:
`<h1>My Application</h1>
<select [(ngModel)]="selectedValue">
<option *ngFor="#c of countries" value="c.id">{{c.name}}</option>
</select>`
})
export class AppComponent{
countries = [
{id: 1, name: "United States"},
{id: 2, name: "Australia"}
{id: 3, name: "Canada"},
{id: 4, name: "Brazil"},
{id: 5, name: "England"}
];
selectedValue = null;
}
이 경우, 다음과 같이 나타납니다.selectedValue
숫자 - 선택한 항목의 ID입니다.
하지만, 저는 실제로 국가 개체 자체에 바인딩하여 다음과 같이 하고 싶습니다.selectedValue
ID 뿐만 아니라 객체입니다.다음과 같이 옵션의 값을 변경하려고 했습니다.
<option *ngFor="#c of countries" value="c">{{c.name}}</option>
하지만 이것은 효과가 없는 것 같습니다.그것은 내 안에 물체를 두는 것처럼 보입니다.selectedValue
하지만 제가 기대하는 대상은 아닙니다.이것은 제 플런커의 예에서 볼 수 있습니다.
또한 선택한 ID를 기반으로 개체를 직접 설정할 수 있도록 변경 이벤트에 바인딩하려고 했습니다. 그러나 바인딩 모델이 업데이트되기 전에 변경 이벤트가 실행되는 것 같습니다. 즉, 해당 시점에서 새로 선택한 값에 액세스할 수 없습니다.
Angular 2를 사용하여 선택한 요소를 객체에 바인딩하는 깨끗한 방법이 있습니까?
<h1>My Application</h1>
<select [(ngModel)]="selectedValue">
<option *ngFor="let c of countries" [ngValue]="c">{{c.name}}</option>
</select>
참고: 사용할 수 있습니다.[ngValue]="c"
대신에[ngValue]="c.id"
여기서 c는 완전한 국가 객체입니다.
[value]="..."
문자열 값만 지원합니다.
[ngValue]="..."
모든 유형 지원
갱신하다
만약에value
개체이므로 미리 선택한 인스턴스가 값 중 하나와 동일해야 합니다.
4.0.0-208.7 이후에 제공된 최근 추가된 사용자 지정 비교 https://github.com/angular/angular/issues/13268 도 참조하십시오.
<select [compareWith]="compareFn" ...
액세스할 경우 처리합니다.this
이내에compareFn
.
compareFn = this._compareFn.bind(this);
// or
// compareFn = (a, b) => this._compareFn(a, b);
_compareFn(a, b) {
// Handle compare logic (eg check if unique ids are the same)
return a.id === b.id;
}
이는 다음과 같은 도움이 될 수 있습니다.
<select [(ngModel)]="selectedValue">
<option *ngFor="#c of countries" [value]="c.id">{{c.name}}</option>
</select>
사용할 필요 없이 이 작업도 수행할 수 있습니다.[(ngModel)]
당신의<select>
꼬리표를 달다
ts 파일에 변수 선언
toStr = JSON.stringify;
그리고 당신의 템플릿에서 이것을 하라.
<option *ngFor="let v of values;" [value]="toStr(v)">
{{v}}
</option>
그런 다음 사용합니다.
let value=JSON.parse(event.target.value)
문자열을 다시 유효한 JavaScript 개체로 구문 분석합니다.
제게 효과가 있었습니다.
템플릿 HTML:
추가했습니다.(ngModelChange)="selectChange($event)"
나에게select
.
<div>
<label for="myListOptions">My List Options</label>
<select (ngModelChange)="selectChange($event)" [(ngModel)]=model.myListOptions.id >
<option *ngFor="let oneOption of listOptions" [ngValue]="oneOption.id">{{oneOption.name}}</option>
</select>
</div>
component.ts에서:
listOptions = [
{ id: 0, name: "Perfect" },
{ id: 1, name: "Low" },
{ id: 2, name: "Minor" },
{ id: 3, name: "High" },
];
추가해야 할 항목component.ts
이 기능:
selectChange( $event) {
//In my case $event come with a id value
this.model.myListOptions = this.listOptions[$event];
}
참고: 사용해 봅니다.[select]="oneOption.id==model.myListOptions.id"
그리고 일이 아닙니다.
다른 방법으로는 =========이 있습니다.
템플릿 HTML:
추가했습니다.[compareWith]="compareByOptionId
나에게select
.
<div>
<label for="myListOptions">My List Options</label>
<select [(ngModel)]=model.myListOptions [compareWith]="compareByOptionId">
<option *ngFor="let oneOption of listOptions" [ngValue]="oneOption">{{oneOption.name}}</option>
</select>
</div>
component.ts에서:
listOptions = [
{ id: 0, name: "Perfect" },
{ id: 1, name: "Low" },
{ id: 2, name: "Minor" },
{ id: 3, name: "High" },
];
추가해야 할 항목component.ts
이 기능:
/* Return true or false if it is the selected */
compareByOptionId(idFist, idSecond) {
return idFist && idSecond && idFist.id == idSecond.id;
}
반응형 양식을 사용하여 동일한 작업을 수행하려는 경우:
<form [formGroup]="form">
<select formControlName="country">
<option *ngFor="let country of countries" [ngValue]="country">{{country.name}}</option>
</select>
<p>Selected Country: {{country?.name}}</p>
</form>
여기에서 작업 예제를 확인하십시오.
인app.component.html
:
<select type="number" [(ngModel)]="selectedLevel">
<option *ngFor="let level of levels" [ngValue]="level">{{level.name}}</option>
</select>
그리고.app.component.ts
:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
levelNum:number;
levels:Array<Object> = [
{num: 0, name: "AA"},
{num: 1, name: "BB"}
];
toNumber(){
this.levelNum = +this.levelNum;
console.log(this.levelNum);
}
selectedLevel = this.levels[0];
selectedLevelCustomCompare = {num: 1, name: "BB"}
compareFn(a, b) {
console.log(a, b, a && b && a.num == b.num);
return a && b && a.num == b.num;
}
}
저는 이렇게 작동합니다. 당신은 위로할 수 있습니다.event.target.value
.
<select (change) = "ChangeValue($event)" (ngModel)="opt">
<option *ngFor=" let opt of titleArr" [value]="opt"></option>
</select>
핵심은 양방향 바인딩을 사용하는 것입니다.select
경유로[(ngModel)]
및 사용[ngValue]
각각의option
.
기본 null 옵션을 사용할 수도 있으며 Angular 12와 함께 작동합니다.
<select name="typeFather" [(ngModel)]="selectedType">
<option [ngValue]="null">Select a type</option>
<option *ngFor="let type of types" [ngValue]="type">{{type.title}}</option>
</select>
이러한 접근 방식은 항상 사용할 수 있지만 동적 목록이 있는 경우 모델보다 먼저 로드해야 합니다.
기능을 사용하여 ID를 선택할 수 있습니다.
<option *ngFor="#c of countries" (change)="onchange(c.id)">{{c.name}}</option>
선택한 항목에 대해 다른 게터 만들기
<form [formGroup]="countryForm">
<select formControlName="country">
<option *ngFor="let c of countries" [value]="c.id">{{c.name}}</option>
</select>
<p>Selected Country: {{selectedCountry?.name}}</p>
</form>
ints:
get selectedCountry(){
let countryId = this.countryForm.controls.country.value;
let selected = this.countries.find(c=> c.id == countryId);
return selected;
}
또한, 주어진 솔루션에서 다른 것이 작동하지 않는 경우, "AppModule" 내의 "FormsModule"을 가져왔는지 확인하십시오. 이것은 저에게 중요한 사항입니다.
선택한 값을 함수를 통해 전달하여 클릭()의 도움을 받아 선택한 값을 얻을 수도 있습니다.
<md-select placeholder="Select Categorie"
name="Select Categorie" >
<md-option *ngFor="let list of categ" [value]="list.value" (click)="sub_cat(list.category_id)" >
{{ list.category }}
</md-option>
</md-select>
이 방법을 사용하기도 합니다.
<h1>My Application</h1>
<select [(ngModel)]="selectedValue">
<option *ngFor="let c of countries" value="{{c.id}}">{{c.name}}</option>
</select>
Angular 2+ 사용자에게 주의: 어떤 이유로 [value]가 요소에서 작동하지 않습니다.대신 [ngModel]을(를) 사용합니다.
<select [ngModel]="selectedCountry">
<option *ngFor="let country of countries" [value]="country">{{country.name}}</option>
</select>
Angular 11에서 테스트됨.'typeSelected' 개체가 추가로 필요합니다.주의: 다른 답변처럼 [(ngValue)]을(를) 사용하지 않습니다.
<mat-select formControlName="type" [(value)]="typeSelected"
[compareWith]="typeComparation">
<mat-option *ngFor="let myType of allSurveysTypes" [value]="myType">
{{myType.title}}
</mat-option>
</mat-select>
//Declaration.
typeSelected: SurveyType;
...
//Assigning variable 'type' of object 'survey' to 'typeSelected'.
this.typeSelected = survey?.type;
...
//Function to compare SurveyType objects.
typeComparation = ( option, value ) => {
if (option && value) {
return option.id === value.id;
}
}
이 코드는 매우 간단합니다.
<select class="form-control" id="marasemaat" [(ngModel)]="fullNamePresentor"
[formControl]="stateControl" (change)="onSelect($event.target.value)">
<option *ngFor="let char of programInfo1;let i = index;"
onclick="currentSlide(9,false)"
value={{char.id}}>{{char.title + " "}} ----> {{char.name + " "+ char.family }} ---- > {{(char.time.split('T', 2)[1]).split(':',2)}}</option>
</select>
언급URL : https://stackoverflow.com/questions/35945001/binding-select-element-to-object-in-angular
'programing' 카테고리의 다른 글
Visual Basic에서 클래스 생성자를 구현하는 방법은 무엇입니까? (0) | 2023.05.11 |
---|---|
.git는 제외 폴더를 무시하지만 특정 하위 폴더를 포함합니다. (0) | 2023.05.11 |
C#에서 두 개 이상의 목록을 하나로 병합합니다.그물 (0) | 2023.05.11 |
URL에서 파일 확장자를 가져올 수 있는 방법이 있습니까? (0) | 2023.05.11 |
XAML에서 색상을 브러시로 변환하려면 어떻게 해야 합니까? (0) | 2023.05.06 |