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

运行结果:

相关推荐
Katzelala18 小时前
[K8S学习笔记] Service和Ingress的关系
笔记·学习·kubernetes
面向星辰19 小时前
html各种常用标签
前端·javascript·html
梦65019 小时前
HTML新属性
前端
递归不收敛20 小时前
PyCharm项目上传GitHub仓库(笔记)
笔记·pycharm·github
递归不收敛20 小时前
一、Java 基础入门:从 0 到 1 认识 Java(详细笔记)
java·开发语言·笔记
东风西巷20 小时前
PDFgear:免费全能的PDF处理工具
前端·pdf·软件需求
森之鸟21 小时前
Mac电脑上如何打印出字体图标
前端·javascript·macos
xian_wwq21 小时前
【学习笔记】Https证书如何升级到国密
笔记·学习·证书
mCell1 天前
GSAP 入门指南
前端·javascript·动效
gnip1 天前
组件循环引用依赖问题处理
前端·javascript