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

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

运行结果:

在这里插入图片描述

相关推荐

最近更新

  1. TCP协议是安全的吗?

    2023-12-28 18:12:03       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-28 18:12:03       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-28 18:12:03       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-28 18:12:03       18 阅读

热门阅读

  1. GetLastError()详细介绍

    2023-12-28 18:12:03       31 阅读
  2. Linux世界的奇妙之旅:开源之道的探索与分享

    2023-12-28 18:12:03       38 阅读
  3. linux查看网卡是100M还是1000M

    2023-12-28 18:12:03       35 阅读
  4. Kafka

    Kafka

    2023-12-28 18:12:03      34 阅读
  5. Android系统启动-init进程详解(Android 14)

    2023-12-28 18:12:03       27 阅读
  6. Qt底层机制之对象树总结

    2023-12-28 18:12:03       33 阅读
  7. 2023年湘潭大学软件工程考试总结

    2023-12-28 18:12:03       37 阅读
  8. 说一下 spring mvc 运行流程?

    2023-12-28 18:12:03       29 阅读
  9. Cnas认证路上你关心的那些个问题

    2023-12-28 18:12:03       33 阅读
  10. 2024 Python开发者转型Go开发

    2023-12-28 18:12:03       29 阅读
  11. linux使用内核编译其中一个模块

    2023-12-28 18:12:03       33 阅读