반응형
    
    
    
  NgFor에서 Ng 모델을 사용한 각도 2 - 2방향 바인딩
Angular 2에서 어떻게 NgFor를 사용하여 반복 목록 내에서 NgModel과 양방향 바인딩을 얻을 수 있습니까?아래는 제 플런크와 코드인데 오류가 발생합니다.
@Component({
  selector: 'my-app',
  template: `
  <div>
    <div *ngFor="let item of toDos;let index = index;">
      <input [(ngModel)]="item" placeholder="item">
    </div>
    Below Should be binded to above input box
    <div *ngFor="let item of toDos">
      <label>{{item}}</label>
    </div>
  </div>
  `,
  directives: [MdButton, MdInput]
})
export class AppComponent { 
  toDos: string[] =["Todo1","Todo2","Todo3"];
  constructor() {}
  ngOnInit() {
  }
}
땅을 판 후에 저는 ByongFor라는 트랙을 사용해야 합니다.아래의 plnkr 및 코드가 업데이트되었습니다.
@Component({
  selector: 'my-app',
  template: `
  <div>
    <div *ngFor="let item of toDos;let index = index;trackBy:trackByIndex;">
      <input [(ngModel)]="toDos[index]" placeholder="item">
    </div>
    Below Should be binded to above input box
    <div *ngFor="let item of toDos">
      <label>{{item}}</label>
    </div>
  </div>
  `,
  directives: [MdButton, MdInput]
})
export class AppComponent { 
  toDos: string[] =["Todo1","Todo2","Todo3"];
  constructor() {}
  ngOnInit() {
  }
  trackByIndex(index: number, obj: any): any {
    return index;
  }
}
당신이 한 일은 두 가지 이유 때문에 작동하지 않습니다.
- ngModel이 있는 항목 대신 toDos[index]를 사용해야 합니다(자세한 내용은 읽기).
 - 각 입력에는 고유한 이름이 있어야 합니다.
 
문제를 해결할 수 있는 해결책이 여기 있습니다.
<div>
<div *ngFor="let item of toDos;let index = index;">
  <input name=a{{index}} [(ngModel)]="toDos[index]" placeholder="item">
</div>
Below Should be binded to above input box
<div *ngFor="let item of toDos">
  <label>{{item}}</label>
</div>
 
사용해 보세요.
@Component({
  selector: 'my-app',
  template: `
  <div>
    <div *ngFor="let item of toDos;let index = index;">
  <input [(ngModel)]="item.text" placeholder="item.text">
    </div>
    Below Should be binded to above input box
    <div *ngFor="let item of toDos">
  <label>{{item.text}}</label>
    </div>
  </div>
  `,
  directives: [MdButton, MdInput]
   })
export class AppComponent { 
  toDos: any[] =[{text:"Todo1"},{text:"Todo2"},{text:"Todo3"}];
  constructor() {}
  ngOnInit() {
  }
}
ngModel을 고유하게 만들려면 ngModel에 name + index로 ngModel 속성을 추가해야 합니다.
<mat-form-field
  #fileNameRef
  appearance="fill"
  color="primary"
  floatLabel="auto"
>
  <input
    matInput
    #fileNameCtrl="ngModel"
    name="originalName{{ index }}"
    [(ngModel)]="file.originalName"
    type="text"
    autocomplete="off"
    autocapitalize="off"
    readonly
  /> 
</mat-form-field>
언급URL : https://stackoverflow.com/questions/40314732/angular-2-2-way-binding-with-ngmodel-in-ngfor
반응형
    
    
    
  'programing' 카테고리의 다른 글
| utf8mb4를 사용하는 경우에도 테이블에 Go-buff-driver 문자열을 삽입하면 1336 오류가 발생합니다. (0) | 2023.07.25 | 
|---|---|
| MariaDB 10.2, jdbc ComplianceTruncation=false가 작동하지 않음 (0) | 2023.07.25 | 
| PowerShell & 출력의 개별 라인에 타임스탬프를 추가하려면 어떻게 해야 합니까? (0) | 2023.07.25 | 
| 명령줄 출력 업데이트(즉, 진행 (0) | 2023.07.25 | 
| %in%의 반대: 벡터에 지정된 값이 있는 행 제외 (0) | 2023.06.15 |