[Angular] 笔记 13:模板驱动表单 - 单选按钮

Radio Buttons (Template Driven Forms)

Radio Button, input 元素类型全部为 radio,因为是单选,name 属性值必须相同。

pokemon-template-form.component.html:

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:

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;
    });
  }
}

运行结果:

相关推荐
蒸蒸yyyyzwd6 小时前
day3学习笔记
笔记·学习
升鲜宝供应链及收银系统源代码服务7 小时前
《IntelliJ + Claude Code + Gemini + ChatGPT 实战配置手册升鲜宝》
java·前端·数据库·chatgpt·供应链系统·生鲜配送
i建模7 小时前
将Edge浏览器的标签页从顶部水平排列**移至左侧垂直侧边栏
前端·edge
跟着珅聪学java7 小时前
js编写中文转unicode 教程
前端·javascript·数据库
英俊潇洒美少年7 小时前
Vue3 深入响应式系统
前端·javascript·vue.js
小陈phd8 小时前
系统架构师学习笔记(三)——计算机体系结构之存储系统
笔记·学习·系统架构
英俊潇洒美少年9 小时前
React 最核心 3 大底层原理:Fiber + Diff + 事件系统
前端·react.js·前端框架
我命由我123459 小时前
React Router 6 - 概述、基础路由、重定向、NavLink、路由表
前端·javascript·react.js·前端框架·ecmascript·html5·js
LJianK19 小时前
java封装
java·前端·数据库
yaaakaaang9 小时前
(四)前端,如此简单!---Promise
前端·javascript