[Angular] 笔记 16:模板驱动表单 - 选择框与选项
2023-12-29 18:34:31
油管视频: 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 type
pokemonType: 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>
<input
type="radio"
name="isCool"
[value]="true"
#pokemonName="ngModel"
[ngModel]="pokemon.isCool"
/>Pokemon is cool?
</label>
<label>
<input
type="radio"
name="isCool"
[value]="false"
[ngModel]="pokemon.isCool"
(ngModelChange)="toggleIsCool($event)"
/>Pokemon is NOT cool?
</label>
<label>
<input
type="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"
:
文章来源:https://blog.csdn.net/ftell/article/details/135276388
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!