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

运行结果:

相关推荐
今儿敲了吗2 分钟前
面向对象(二)——UML基础
笔记·uml
sheeta199810 分钟前
Vue 前端基础笔记
前端·vue.js·笔记
小小小小宇10 分钟前
GitLab + GitLab Runner + Qiankun 微前端 + Nginx + Node 中间件 前端开发机从零搭建 CI/CD 全流程
前端
哆哆啦0012 分钟前
obsidian远程同步方案:infiniCloud+remotely save方案
笔记·git·obsidian
前端那点事15 分钟前
别再写垃圾组件!Vue3 如何设计「真正可复用」的高质量通用组件
前端·vue.js
卷帘依旧18 分钟前
JavaScript 中的 Symbol
前端·javascript
老王以为22 分钟前
Claude Code 从 GUI 到 TUI:开发者界面的范式回归
前端·人工智能·全栈
JYeontu23 分钟前
正方体翻滚Loading 2.0
前端·javascript·css
llq_35024 分钟前
React 组件处理 Props
前端
夫子39625 分钟前
多人协同后内容丢失?一文搞懂ONLYOFFICE document.key的正确用法
前端