* ng用于在Angular表单中添加空白来选择



在Angular表单中使用*ngFor循环是在select项的前后添加空白。这会导致下游代码中的错误,因为它很难在选择中修补或设置值(即从用于预填充表单的数据库中存储的值)。Angular版本12.1.4.

如果我只是在离子选择中手动输入数据,则不会发生这种情况。

那么两个问题:为什么会发生这种情况,以及如何摆脱这种行为?

home.page.ts:

import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from "@angular/forms";
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
public nameForm = new FormGroup({
name: new FormControl('', Validators.required),
name1: new FormControl('', Validators.required),
});
nameList: string[] = ['Louise','Nancy','Kate'];
constructor(){}
public onSubmit() {
console.log("Does name1 have whitespace???", this.nameForm.value);
}
}

home。

<ion-content>
<form [formGroup]="nameForm" (ngSubmit)="onSubmit()">
<ion-item>
<ion-label>Choose name</ion-label>
<ion-select formControlName="name">
<ion-select-option>Louise</ion-select-option>
<ion-select-option>Nancy</ion-select-option>
<ion-select-option>Kate</ion-select-option>
</ion-select>
</ion-item>
<ion-item>
<ion-label>Choose name1</ion-label>
<ion-select formControlName="name1">
<ion-select-option *ngFor="let n of nameList">
{{n}}
</ion-select-option>
</ion-select>
</ion-item>
<button type="submit">Submit</button>
</form>
</ion-content>

home.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { IonicModule } from '@ionic/angular';
import { FormsModule } from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';
import { HomePage } from './home.page';
import { HomePageRoutingModule } from './home-routing.module';
@NgModule({
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule,
IonicModule,
HomePageRoutingModule
],
declarations: [HomePage]
})
export class HomePageModule {}

console log output:

name1有空格吗??{name: 'Louise', name1: 'Louise'}

更新:我想知道这是否是我做html的方式中的新行问题。是的,如果它被改成:

<ion-select-option *ngFor="let n of nameList">{{n}}</ion-select-option>

我得到没有空格的值!

name1有空格吗??{名称:"Louise"name1:"Louise"

最新更新