import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <form #loginForm="ngForm"> Angular版本: <div *ngFor="let version of versions;"> <input [attr.id]="version" ngModel required [value]="version" type="radio"> <label [attr.for]="version">{{version}}</label> </div> <hr> {{loginForm.value | json}} </form> `, }) export class AppComponent { versions = ['1.x', '2.x', '3.x']; }
第九节 - 使用多选控件
如何添加多选控件?
在 Angular 中,我们通过 <select> 方式添加多选控件。
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <form #loginForm="ngForm"> Angular版本: <select [ngModel]="versions[0]"> <option *ngFor="let version of versions;" [value]="version"> {{version}} </option> </select> <hr> {{loginForm.value | json}} </form> `, }) export class AppComponent { versions = ['1.x', '2.x', '3.x']; }
如何添加必填验证?
import { Component } from '@angular/core'; @Component({ selector: 'app-root', styles: [` select.ng-invalid + label:after { content: '<-- 请选择版本!' } ` ], template: ` <form #loginForm="ngForm"> Angular版本: <div> <select [ngModel]="version" required> <option *ngFor="let version of versions;" [value]="version"> {{version}} </option> </select> <label></label> </div> <hr> {{loginForm.value | json}} </form> `, }) export class AppComponent { versions = ['','1.x', '2.x', '3.x']; }