面试题答案
一键面试HTML模板代码
<form #myForm="ngForm">
<input type="text" name="username" [(ngModel)]="user.username" required>
<div *ngIf="myForm.controls['username']?.hasError('required') && (myForm.controls['username'].touched || myForm.controls['username'].dirty)">
用户名是必填项
</div>
<button type="submit">提交</button>
</form>
TS代码片段
通常在模板驱动表单中,TS代码无需额外写针对此验证的逻辑,因为Angular内置指令已经处理。但如果组件类中有相关逻辑,可能如下:
import { Component } from '@angular/core';
@Component({
selector: 'app-my-form',
templateUrl: './my-form.component.html',
styleUrls: ['./my-form.component.css']
})
export class MyFormComponent {
user = { username: '' };
}