Angular 2의 "select"에서 새 선택을 받으려면 어떻게 해야 합니까?
Angular 2(Type Script)를 사용하고 있습니다.
새로운 선곡으로 뭔가를 하고 싶지만, 내가 얻은 것은onChange()항상 마지막 선택입니다.새로운 선택을 받으려면 어떻게 해야 하나요?
<select [(ngModel)]="selectedDevice" (change)="onChange($event)">
<option *ngFor="#i of devices">{{i}}</option>
</select>
onChange($event) {
console.log(this.selectedDevice);
// I want to do something here with the new selectedDevice, but what I
// get here is always the last selection, not the one I just selected.
}
양방향 데이터 바인딩이 필요하지 않은 경우:
<select (change)="onChange($event.target.value)">
<option *ngFor="let i of devices">{{i}}</option>
</select>
onChange(deviceValue) {
console.log(deviceValue);
}
양방향 데이터 바인딩의 경우 이벤트 바인딩과 속성 바인딩을 구분합니다.
<select [ngModel]="selectedDevice" (ngModelChange)="onChange($event)" name="sel2">
<option [value]="i" *ngFor="let i of devices">{{i}}</option>
</select>
export class AppComponent {
devices = 'one two three'.split(' ');
selectedDevice = 'two';
onChange(newValue) {
console.log(newValue);
this.selectedDevice = newValue;
// ... do other stuff here ...
}
한다면devices오브젝트 배열, 바인드ngValue대신value:
<select [ngModel]="selectedDeviceObj" (ngModelChange)="onChangeObj($event)" name="sel3">
<option [ngValue]="i" *ngFor="let i of deviceObjects">{{i.name}}</option>
</select>
{{selectedDeviceObj | json}}
export class AppComponent {
deviceObjects = [{name: 1}, {name: 2}, {name: 3}];
selectedDeviceObj = this.deviceObjects[1];
onChangeObj(newObj) {
console.log(newObj);
this.selectedDeviceObj = newObj;
// ... do other stuff here ...
}
}
Plunker - 사용 안 함<form>
Plunker - 용도<form>새로운 형식의 API를 사용합니다.
선택 태그에 참조 변수를 생성하여 값을 컴포넌트에 다시 전달할 수 있습니다.#device변경 핸들러에 전달하다onChange($event, device.value)새로운 가치를 가져야 한다
<select [(ng-model)]="selectedDevice" #device (change)="onChange($event, device.value)">
<option *ng-for="#i of devices">{{i}}</option>
</select>
onChange($event, deviceValue) {
console.log(deviceValue);
}
[value] 대신 [ngValue]만 사용하세요!
export class Organisation {
description: string;
id: string;
name: string;
}
export class ScheduleComponent implements OnInit {
selectedOrg: Organisation;
orgs: Organisation[] = [];
constructor(private organisationService: OrganisationService) {}
get selectedOrgMod() {
return this.selectedOrg;
}
set selectedOrgMod(value) {
this.selectedOrg = value;
}
}
<div class="form-group">
<label for="organisation">Organisation
<select id="organisation" class="form-control" [(ngModel)]="selectedOrgMod" required>
<option *ngFor="let org of orgs" [ngValue]="org">{{org.name}}</option>
</select>
</label>
</div>
https://angular.io/docs/ts/latest/guide/forms.html에서 Angular 2 폼 튜토리얼(TypeScript 버전)을 실행하다가 이 문제가 발생했습니다.
선택/옵션 블록에서 옵션 중 하나를 선택하여 선택 항목의 값을 변경할 수 없습니다.
Mark Rajcok이 제안한 것을 실행한 것은 효과가 있었습니다만, 오리지날 튜토리얼에서 놓친 것이 있는지, 갱신이 있었는지 궁금합니다.어떤 경우에도 추가
onChange(newVal) {
this.model.power = newVal;
}
HeroFormComponent 클래스의 hero-form.component.ts로 이동합니다.
그리고.
(change)="onChange($event.target.value)"
에서 hero-form.component.component.display를<select>요소가 그것을 작동시켰다.
선택 각도 6 이상에서 변경.예(selectionChange)= onChange($event.value)
저도 같은 문제가 있어서 아래 코드를 사용하여 해결했습니다.
(change)="onChange($event.target.value)"
Angular 8에서는 "selectionChange"를 다음과 같이 간단히 사용할 수 있습니다.
<mat-select [(value)]="selectedData" (selectionChange)="onChange()" >
<mat-option *ngFor="let i of data" [value]="i.ItemID">
{{i.ItemName}}
</mat-option>
</mat-select>
각도 7/8
angular 6을 기준으로 반응형 지시가 있는 ngModel 입력 속성은 사용되지 않으며 angular 7+에서 모두 제거되었습니다.공식 문서를 읽어보십시오.
사후 대응형 어프로치를 사용하면 선택한 데이터를 다음과 같이 취득/설정할 수 있습니다.
//in your template
<select formControlName="person" (change)="onChange($event)"class="form-control">
<option [value]="null" disabled>Choose person</option>
<option *ngFor="let person of persons" [value]="person">
{{person.name}}
</option>
</select>
//in your ts
onChange($event) {
let person = this.peopleForm.get("person").value
console.log("selected person--->", person);
// this.peopleForm.get("person").setValue(person.id);
}
또 다른 옵션은 오브젝트를 문자열로 값 안에 저장하는 것입니다.
<select [ngModel]="selectedDevice | json" (ngModelChange)="onChange($event)">
<option [value]="i | json" *ngFor="let i of devices">{{i}}</option>
</select>
컴포넌트:
onChange(val) {
this.selectedDevice = JSON.parse(val);
}
이것이 페이지 로드 시 선택값을 설정하기 위해 양방향 바인딩 작업을 수행할 수 있는 유일한 방법입니다.이는 선택 상자를 채우는 목록이 바인딩된 개체와 완전히 동일하지 않고 동일한 속성 값뿐만 아니라 동일한 개체여야 하기 때문입니다.
양방향 데이터 바인딩이 필요하지 않은 경우:
<select (change)="updateSorting($event)">
<option disabled selected>Sorting</option>
<option value="pointDes">pointDes</option>
<option value="timeDes">timeDes</option>
<option value="timeAsc">timeAsc</option>
<option value="pointAsc">pointAsc</option>
</select>
updateSorting(e: any) {
// console.log((e.target as HTMLSelectElement)?.value); // also work
console.log(e.target.value);
}
<mat-form-field>
<mat-select placeholder="Vacancies" [(ngModel)]="vacanciesSpinnerSelectedItem.code" (ngModelChange)="spinnerClick1($event)"
[ngModelOptions]="{standalone: true}" required>
<mat-option *ngFor="let spinnerValue of vacanciesSpinnerValues" [value]="spinnerValue?.code">{{spinnerValue.description}}</mat-option>
</mat-select>
angular Material 드롭다운에 사용했는데 잘 작동합니다.
모든 제안을 시도해 봤지만 아무 것도 통하지 않아요.
예를 들어 양방향 바인딩이 필요하고 NUMBER 값이 있는 룩업이 있으며 이 룩업의 값으로 SELECT를 채우고 선택한 옵션을 강조 표시해야 하는 상황을 상상해 보십시오.
[value] 또는 (ngModelChange)는 사용자가 변경을 시작한 후 선택한 옵션을 선택할 수 없기 때문에 사용할 수 없습니다.[value]는 (ngModelChange)에 대해 모든 것을 문자열로 간주하기 때문에 사용자가 변경을 시작할 때 사용해서는 안 되기 때문에 적절한 선택을 할 수 없습니다.[ngModel]을 사용하면 수신된 VALUE의 고정 형식이 INDEX: VALUE로 보장되고 그에 따라 쉽게 해석할 수 있지만 다시 한 번 선택하신 옵션이 폐기됩니다.
따라서 [ngValue](적절한 타입을 취급한다), (변경) 및...[VALUE]: 핸들러가 DISPLAYED VALUE 또는 INDEX: VALUE가 아닌 VALUE를 수신할 수 있도록 합니다.다음은 작업상의 서투른 솔루션입니다.
<select
class="browser-default custom-select"
(change)="onEdit($event.target.value)"
>
<option [value]="">{{
'::Licences:SelectLicence' | abpLocalization
}}</option>
<ng-container *ngIf="licencesLookupData$ | async">
<option
*ngFor="let l of licencesLookupData$ | async"
[ngValue]="l.id"
[value]="l.id"
[selected]="l.id == selected.id"
>
{{ l.id }} {{ l.displayName | defaultValue }}
</option>
</ng-container>
</select>
onEdit(idString: string) {
const id = Number(idString);
if (isNaN(id)) {
this.onAdd();
return;
}
this.licencesLoading = true;
this.licencesService
.getById(id)
.pipe(finalize(() => (this.licencesLoading = false)), takeUntil(this.destroy))
.subscribe((state: Licences.LicenceWithFlatProperties) => {
this.selected = state;
this.buildForm();
this.get();
});
}
최신 ionic 3.2.0은 (ionChange)로 변경(변경)되었습니다.
예: HTML
<ion-select (ionChange)="function($event)"> <ion-option>1<ion-option>
</ion-select>
TS
function($event){
// this gives the selected element
console.log($event);
}
Angular 5에서 다음과 같은 방법으로 수행했습니다. $event.target.value 대신 $event.value 객체를 가져옵니다.
<mat-form-field color="warn">
<mat-select (ngModelChange)="onChangeTown($event)" class="form-width" formControlName="branch" [(ngModel)]="branch" placeholder="Enter branch">
<mat-option *ngFor="let branch of branchs" [value]="branch.value">
{{ branch.name }}
</mat-option>
</mat-select>
</mat-form-field>
onChangeTown(event): void {
const selectedTown = event;
console.log('selectedTown: ', selectedTown);
}
언급URL : https://stackoverflow.com/questions/33700266/how-can-i-get-new-selection-in-select-in-angular-2
'programing' 카테고리의 다른 글
| 값이 = "value1" 또는 "value2"인 스프링 @ConditionalOnProperty (0) | 2023.02.23 |
|---|---|
| 스크롤 뷰 내부 뷰가 작동하지 않는 반응 네이티브 (0) | 2023.02.23 |
| 스프링: 정적 필드에 값을 주입하려면 어떻게 해야 합니까? (0) | 2023.02.23 |
| Junit-vintage-engine과 Junit-jupiter-engine의 차이점은 무엇입니까? (0) | 2023.02.23 |
| 각도 2/4/5가 IE11에서 작동하지 않음 (0) | 2023.02.23 |