gpt4 book ai didi

angular - formControlName 和 FormControl 有什么区别?

转载 作者:太空狗 更新时间:2023-10-29 16:45:43 35 4
gpt4 key购买 nike

我正在使用 Angular2 的 ReactiveFormsModule 创建一个包含表单的组件。这是我的代码:

foo.component.ts:

constructor(fb: FormBuilder) {
this.myForm = fb.group({
'fullname': ['', Validators.required],
'gender': []
});
}

foo.component.html(使用 [formControl]):

<div class="fields">
<div class="field">
<label>Fullname*</label>
<input type="text" [formControl]="myForm.controls.fullname"/>
</div>
</div>

<div class="inline fields">
<label for="gender">Gender</label>
<div class="field">
<div class="ui radio checkbox">
<input type="radio" name="gender" checked="" tabindex="0" class="hidden" [formControl]="myForm.controls.gender">
<label>Male</label>
</div>
</div>
<div class="field">
<div class="ui radio checkbox">
<input type="radio" name="gender" tabindex="0" class="hidden" [formControl]="myForm.controls.gender">
<label>Female</label>
</div>
</div>
</div>

foo.component.html(带有 formControlName):

<div class="fields">
<div class="field">
<label>Fullname*</label>
<input type="text" formControlName="fullname"/>
</div>
</div>

<div class="inline fields">
<label for="gender">Gender</label>
<div class="field">
<div class="ui radio checkbox">
<input type="radio" name="gender" checked="" tabindex="0" class="hidden" formControlName="gender">
<label>Male</label>
</div>
</div>
<div class="field">
<div class="ui radio checkbox">
<input type="radio" name="gender" tabindex="0" class="hidden" formControlName="gender">
<label>Female</label>
</div>
</div>
</div>

两种方式都有效。但我不知道使用 [formControl]formControlName 有什么区别。

最佳答案

我相信您错过了重要的一点:第二个示例中的 [formGroup] 指令。 formControlName[formGroup] 一起使用以保存您的表单多点导航。例如:

<div>
<input type="text" [formControl]="myForm.controls.firstName"/>
<input type="text" [formControl]="myForm.controls.lastName"/>
<input type="text" [formControl]="myForm.controls.email"/>
<input type="text" [formControl]="myForm.controls.title"/>
</div>

相当于:

<div [formGroup]="myForm">
<input type="text" formControlName="firstName"/>
<input type="text" formControlName="lastName"/>
<input type="text" formControlName="email"/>
<input type="text" formControlName="title"/>
</div>

现在想象一下嵌套的 FormGroups :)

关于angular - formControlName 和 FormControl 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40171914/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com