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

运行结果:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值