油管视频: Select & Option (Template Driven Forms)
Select & Option
在 pokemon.ts
中新增 interface:
export interface Pokemon {id: number;name: string;type: string;isCool: boolean;isStylish: boolean;acceptTerms: boolean;
}// new interface
export interface PokemonType {key: number;value: string;
}
修改 pokemon-template-form.component.ts
:
import { Component, OnInit } from '@angular/core';
import { Pokemon, PokemonType } from '../models/pokemon';
import { PokemonService } from '../services/pokemon.service';@Component({selector: 'app-pokemon-template-form',templateUrl: './pokemon-template-form.component.html',styleUrls: ['./pokemon-template-form.component.css'],
})
export class PokemonTemplateFormComponent implements OnInit {pokemon!: Pokemon;// create dropdown for Pokemon typepokemonType: PokemonType[] = [{key: 0,value: 'Fire',},{key: 1,value: 'Water',},];constructor(private pokemonService: PokemonService) {}toggleIsCool(object: any) {console.log(object);this.pokemon.isCool = !this.pokemon.isCool;}ngOnInit() {this.pokemonService.getPokemon(1).subscribe((data: Pokemon) => {this.pokemon = data;});}
}
在 HTML 中显示,pokemon-template-form.component.html:
<form #form="ngForm">Pokemon Name:<input type="text" [(ngModel)]="pokemon.name" name="name" /><label><inputtype="radio"name="isCool"[value]="true"#pokemonName="ngModel"[ngModel]="pokemon.isCool"/>Pokemon is cool?</label><label><inputtype="radio"name="isCool"[value]="false"[ngModel]="pokemon.isCool"(ngModelChange)="toggleIsCool($event)"/>Pokemon is NOT cool?</label><label><inputtype="checkbox"name="acceptTerms"[(ngModel)]="pokemon.acceptTerms"/>Accept Terms?</label><label>Pokemon Type:<select name="pokemonType" [ngModel]="pokemon?.name"><option*ngFor="let type of pokemonType"[value]="type.key"[selected]="type.value === pokemon.type">{{ type.value }}</option></select></label>
</form>
<div>MODEL: {{ pokemon | json }} FORM: {{ form.value | json }} ERROR:<div *ngIf="!pokemonName.pristine">NOT PRINSTINE ANYMORE IT IS DIRTY!</div>
</div>
选择框与下拉列表正常工作:
如果要发送值给后端,那么将 HTML 中的 [value]="type.key"
改为 [value]="type.value"
: