Radio Buttons (Template Driven Forms)
Radio Button, input 元素类型全部为 radio
,因为是单选,name
属性值必须相同。
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"
[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>
</form>
<div>MODEL: {{ pokemon | json }} FORM: {{ form.value | json }}</div>
pokemon-template-form.component.ts
:
import { Component, OnInit } from '@angular/core';
import { Pokemon } 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;
constructor(private pokemonService: PokemonService) {}
// event handler
toggleIsCool(object: any) {
console.log(object);
this.pokemon.isCool = !this.pokemon.isCool;
}
ngOnInit() {
this.pokemonService.getPokemon(1).subscribe((data: Pokemon) => {
this.pokemon = data;
});
}
}
运行结果: