선택 태그(Angular 2)에서 ngModel 변경을 감지하려면 어떻게 해야 합니까?
변경 내용을 검색하는 중입니다.ngModel
순식간에<select>
태그. Angular 1.x에서, 우리는 이것을 해결할 수 있습니다.$watch
에ngModel
또는 를 사용하여ngChange
하지만 나는 아직 어떻게 변화를 감지하는지 이해하지 못합니다.ngModel
각도 2에서
전체 예: http://plnkr.co/edit/9c9oKH1tjDDb67zdKmr9?p=info
import {Component, View, Input, } from 'angular2/core';
import {FORM_DIRECTIVES} from 'angular2/common';
@Component({
selector: 'my-dropdown'
})
@View({
directives: [FORM_DIRECTIVES],
template: `
<select [ngModel]="selection" (ngModelChange)="onChange($event, selection)" >
<option *ngFor="#option of options">{{option}}</option>
</select>
{{selection}}
`
})
export class MyDropdown {
@Input() options;
selection = 'Dog';
ngOnInit() {
console.log('These were the options passed in: ' + this.options);
}
onChange(event) {
if (this.selection === event) return;
this.selection = event;
console.log(this.selection);
}
}
보시다시피, 드롭다운에서 다른 값을 선택하면,ngModel
변경 사항이 표시되고 뷰의 보간된 표현식이 이를 반영합니다.
클래스/컨트롤러의 변경 사항을 어떻게 알립니까?
업데이트:
이벤트 바인딩과 속성 바인딩을 구분합니다.
<select [ngModel]="selectedItem" (ngModelChange)="onChange($event)">
onChange(newValue) {
console.log(newValue);
this.selectedItem = newValue; // don't forget to update the model here
// ... do other stuff here ...
}
사용할 수도 있습니다.
<select [(ngModel)]="selectedItem" (ngModelChange)="onChange($event)">
그러면 이벤트 핸들러에서 모델을 업데이트할 필요가 없지만, 이로 인해 두 개의 이벤트가 발생하므로 효율성이 떨어질 수 있습니다.
베타 버전에서 버그를 수정하기 전의 오래된 답변입니다.1:
로컬 템플릿 변수를 만들고 다음을 연결합니다.(change)
이벤트:
<select [(ngModel)]="selectedItem" #item (change)="onChange(item.value)">
참고 항목Angular 2의 "select"에서 새 선택 항목을 얻는 방법
저는 이 질문을 우연히 발견했고 제가 잘 사용하고 작업한 답변을 제출하겠습니다.나는 객체의 배열과 필터링을 하는 검색 상자를 가지고 있었고 내 검색 상자에서 나는 사용했습니다.(ngModelChange)="onChange($event)"
내 안에서.html
<input type="text" [(ngModel)]="searchText" (ngModelChange)="reSearch(newValue)" placeholder="Search">
그때 내 안에서component.ts
reSearch(newValue: string) {
//this.searchText would equal the new value
//handle my filtering with the new value
}
언급URL : https://stackoverflow.com/questions/34405301/how-do-i-detect-change-to-ngmodel-on-a-select-tag-angular-2
'programing' 카테고리의 다른 글
Bash에서 문자열에서 새 줄을 제거하는 방법 (0) | 2023.04.27 |
---|---|
메이븐 관리 종속성에 대한 Eclipse에 연결된 소스 jar 파일 가져오기 (0) | 2023.04.27 |
현재 실행 중인 리눅스 프로세스를 백그라운드로 어떻게 배치할 수 있습니까? (0) | 2023.04.27 |
npm을 통해 Azure DevOps 아티팩트 피드에 연결하려고 할 때 '인증할 수 없음'; E401 오류가 발생합니다. (0) | 2023.04.27 |
Bash에서 ls를 사용하여 디렉토리만 나열하시겠습니까? (0) | 2023.04.27 |