각도 2 - 드롭다운 목록에서 선택한 값 설정
각도 2의 드롭다운 목록에서 값을 미리 선택하는 데 문제가 생겼습니다.
드롭다운 목록에 성공적으로 바인딩된 구성 요소에 색상 배열을 설정했습니다.페이지에서 값을 미리 선택하는 것이 문제입니다.
[selected]="car.color.id == x.id"
을야다다야ehen에 설정된 값을 선택해야 합니다.this.car.color = new Colour(-1,'');
이 경우 검은색)으로만 작동합니다.는를량상의 ID다만이할나로색우막(이다색만r우ns나ysi할rden(orntd)tthis.car.color = new Colour(4,'');
저는 Angular(rc3)의 최신 버전을 사용하고 있으며 rc1과 rc2에서 동일한 문제를 경험했습니다.
여기 문제를 보여주는 플렁커가 있습니다.
https://plnkr.co/edit/yIVEeLK7PUY4VQFrR48g?p=preview
또 다른 이상한 점은 메타데이터를 볼 때 각도가 선택한 값을 true로 설정했다는 것입니다.
그러나 드롭다운은 여전히 비어 있습니다.
이와 관련된 질문들과는 별개의 문제로 보입니다.
Angular2에서 객체 배열에 select/option/NgFor를 사용하는 방법
안부 전해요
스티브
구성요소 템플릿
<div>
<label>Colour</label>
<div>
<select [(ngModel)]="car.colour"">
<option *ngFor="let x of colours" [value]="x.id" [selected]="car.color.id == x.id">{{x.name}}</option>
</select>
</div>
</div>
요소
import { Component, OnInit } from '@angular/core';
import {AbstractControl,FORM_DIRECTIVES } from '@angular/common';
@Component({
selector:'dropdown',
templateUrl:'app/components/dropdown/dropdown.component.html',
directives:[FORM_DIRECTIVES]
})
export class DropdownComponent implements OnInit
{
car:Car = new Car();
colours = Array<Colour>();
ngOnInit(): void {
this.colours = Array<Colour>();
this.colours.push(new Colour(-1, 'Please select'));
this.colours.push(new Colour(1, 'Green'));
this.colours.push(new Colour(2, 'Pink'));
this.colours.push(new Colour(3, 'Orange'));
this.colours.push(new Colour(4, 'Black'));
this.car = new Car();
this.car.color = new Colour(-1,'');
}
}
export class Car
{
color:Colour;
}
export class Colour
{
constructor(id:number, name:string) {
this.id=id;
this.name=name;
}
id:number;
name:string;
}
설정 car.colour
처음에 선택하려는 값은 일반적으로 작동합니다.
car.colour
설정되어 다를 제거할 수 . 제거할 수 있습니다.[selected]="car.color.id == x.id"
.
이 이 [ngValue]="..."
사용해야 합니다.[value]="..."
문자열만 지원합니다.
각도 2 단순 드롭다운 선택 값
선택한 값만 표시하면 되고 구성 요소에 무언가를 선언할 필요가 없기 때문에 누군가에게 도움이 될 수 있습니다.
상태가 데이터베이스에서 오는 경우 선택한 값을 이 방법으로 표시할 수 있습니다.
<div class="form-group">
<label for="status">Status</label>
<select class="form-control" name="status" [(ngModel)]="category.status">
<option [value]="1" [selected]="category.status ==1">Active</option>
<option [value]="0" [selected]="category.status ==0">In Active</option>
</select>
</div>
귄터의 조언에 감사드립니다. 올바른 방향으로 나아가게 해주었습니다.솔루션에 'color'의 철자가 일치하지 않아 문제가 발생했고 템플릿 html에 'value'가 아닌 'ngValue'를 사용해야 했습니다.
다음은 ngModel 및 select list 옵션에 개체를 사용하고 [selected] 특성을 사용하지 않는 전체 솔루션입니다.
풀 작동 솔루션을 보여주기 위해 Plunker를 업데이트했습니다.https://plnkr.co/edit/yIVEeLK7PUY4VQFrR48g?p=preview
구성요소 템플릿
<div>
<label>Colour</label>
<div *ngIf="car != null">
<select [(ngModel)]="car.colour">
<option *ngFor="let x of colours" [ngValue]="x" >{{x.name}}</option>
</select>
</div>
</div>
요소
import { Component, OnInit } from '@angular/core';
import {AbstractControl,FORM_DIRECTIVES } from '@angular/common';
@Component({
selector:'dropdown',
templateUrl:'app/components/dropdown/dropdown.component.html',
directives:[FORM_DIRECTIVES]
})
export class DropdownComponent implements OnInit
{
car:Car;
colours: Array<Colour>;
ngOnInit(): void {
this.colours = Array<Colour>();
this.colours.push(new Colour(-1, 'Please select'));
this.colours.push(new Colour(1, 'Green'));
this.colours.push(new Colour(2, 'Pink'));
this.car = new Car();
this.car.colour = this.colours[1];
}
}
export class Car
{
colour:Colour;
}
export class Colour
{
constructor(id:number, name:string) {
this.id=id;
this.name=name;
}
id:number;
name:string;
}
이 예제 솔루션은 반응성 형태를 위한 것입니다.
<select formControlName="preferredBankAccountId" class="form-control">
<option *ngFor="let item of societyAccountDtos" [value]="item.societyAccountId" >
{{item.nickName}}
</option>
</select>
구성요소에서:
this.formGroup.patchValue({
preferredBankAccountId: object_id_to_be_pre_selected
});
요구 사항에 따라 폼 그룹 이상을 초기화할 때 이 값을 지정할 수도 있습니다.
폼Control을 초기화할 필요가 없는 경우에도 [(ngModel)] 바인딩을 사용하여 이 작업을 수행할 수 있습니다.
[(ngModel)] 바인딩을 사용한 예제
<select [(ngModel)]="matchedCity" formControlName="city" class="form-control input-sm">
<option *ngFor="let city of cities" [ngValue]="city">{{city.cityName}}</option>
</select>
여기서 matched City는 도시 내 객체 중 하나입니다.
저는 이 정도면 돼요.
<select formControlName="preferredBankAccountId" class="form-control" value="">
<option value="">Please select</option>
<option *ngFor="let item of societyAccountDtos" [value]="item.societyAccountId" >{{item.nickName}}</option>
</select>
이것이 유효한지 아닌지 확실하지 않습니다. 틀리면 수정해주세요.
이런 식으로 하면 안 된다면 수정해 주세요.
제 경우에는 제 apieg: "35"에서 문자열 값을 반환하고 HTML에서 사용하고 있었습니다.
<mat-select placeholder="State*" formControlName="states" [(ngModel)]="selectedState" (ngModelChange)="getDistricts()">
<mat-option *ngFor="let state of formInputs.states" [value]="state.stateId">
{{ state.stateName }}
</mat-option>
</mat-select>
댓글 값에 언급된 다른 사람들처럼 정수 값만 허용할 것입니다.그래서 제가 한 일은 아래와 같이 제 컴포넌트 클래스에서 문자열 값을 정수로 변환한 것입니다.
var x = user.state;
var y: number = +x;
그런 다음에 이렇게 할당했습니다.
this.EditProfileForm.get('states').setValue(y);
이제 기본적으로 올바른 값이 설정됩니다.
실제로 반응형 양식을 사용하면 다음과 같은 작업을 훨씬 쉽게 수행할 수 있습니다.
양식이 다음과 같이 정의되는 경우:
public formName = new FormGroup({
fieldName: new FormControl("test") //where "test is field default value"
});
그러면 값을 변경할 수 있습니다.
this.formName.controls.fieldName.setValue("test 2"); //setting field value to "test 2"
값이 데이터베이스에서 가져온 경우 선택한 값을 표시합니다.
<div class="form-group">
<label for="status">Status</label>
<select class="form-control" name="status" [(ngModel)]="category.status">
<option [value]="1" [selected]="category.status ==1">Active</option>
<option [value]="0" [selected]="category.status ==0">In Active</option>
</select>
</div>
[ngValue]="..."..." 지원 문자열을 추가하고 싶지만 [ngValue]='...'처럼 숫자를 나타내는 경우 간단한 따옴표를 추가해야 합니다.귄터 쇠치바우어의 대답을 보완하기 위해서였습니다.
<div class="col-md-3 col-sm-3">
<label>Outlet Ready</label>
<div>
<select class="form-control"
[(ngModel)]="selectedColor">
<option *ngFor="let x of colours" [ngValue]="x" >{{x.name}}</option>
</select>
</div>
</div>
Component.ts
import { Component, OnInit } from '@angular/core';
import {AbstractControl,FORM_DIRECTIVES } from '@angular/common';
@Component({
selector:'dropdown',
templateUrl:'app/components/dropdown/dropdown.component.html',
directives:[FORM_DIRECTIVES]
})
export class DropdownComponent implements OnInit
{
car:Car;
colours: Array<Colour>;
ngOnInit(): void {
this.colours = Array<Colour>();
this.colours.push(new Colour(-1, 'Please select'));
this.colours.push(new Colour(1, 'Green'));
this.colours.push(new Colour(2, 'Pink'));
this.car = new Car();
this.car.colour = this.colours[1];
}
}
export class Car
{
colour:Colour;
}
export class Colour
{
constructor(id:number, name:string) {
this.id=id;
this.name=name;
}
id:number;
name:string;
잘 작동하고 있어요...:)
언급URL : https://stackoverflow.com/questions/37968712/angular-2-setting-selected-value-on-dropdown-list
'programing' 카테고리의 다른 글
부트스트랩의 '팝오버' 컨테이너에 클래스를 동적으로 추가 (0) | 2023.09.14 |
---|---|
주장을 바탕으로 재스민 스파이를 수정할 수 있는 방법이 있습니까? (0) | 2023.09.09 |
Rxjs to Promise()가 더 이상 사용되지 않습니다. (0) | 2023.09.09 |
SQL Server에서 Oracle로 데이터 반복 이동 (0) | 2023.09.09 |
NSURL 연결에 대해 Xcode 4 경고 "식 결과가 사용되지 않음" (0) | 2023.09.09 |