angular-forms 相关问题

与Angular模板或反应形式相关的问题。

如何将新的`@for`循环语法用于动态表单?

我正在遵循有关动态表单的 Angular 17 指南。在此代码片段中,他们展示了如何使用 ngFor 循环来动态显示表单控件数组。 我正在遵循有关动态表单的 Angular 17 指南。在此代码片段中,他们展示了如何使用 ngFor 循环来动态显示表单控件数组。 <div formArrayName="aliases"> <h2>Aliases</h2> <button type="button" (click)="addAlias()">+ Add another alias</button> <div *ngFor="let alias of aliases.controls; let i=index"> <!-- The repeated alias template --> <label for="alias-{{ i }}">Alias:</label> <input id="alias-{{ i }}" type="text" [formControlName]="i"> </div> </div> 如何使用 Angular 17 中引入的 new @for 循环语法 来代替?我尝试了以下方法: <div formArrayName="aliases"> <h2>Aliases</h2> <button type="button" (click)="addAlias()">+ Add another alias</button> @for (alias of aliases.controls; track $index; let i = $index;) { <div> <!-- The repeated alias template --> <label for="alias-{{ i }}">Alias:</label> <input id="alias-{{ i }}" type="text" [formControlName]="i"> </div> } </div> 但是我得到的错误是Property $index does not exist on ... 我期望使用的 for 循环语法会产生与使用 ngFor 的示例相同的结果。 锯齿存在问题,其中let i = $index;会消除$index,因此无法在轨道上工作: 您可以这样修复它: @for (alias of aliases.controls; let i =$index; track i; ) { <div> <!-- The repeated alias template --> <label for="alias-{{ i }}">Alias:</label> <input id="alias-{{ i }}" type="text" [formControlName]="i"> </div> } 或者更好的是,你甚至不再需要别名,你可以直接使用模板中隐式的$index @for (alias of aliases.controls; track $index) { <div> <!-- The repeated alias template --> <label for="alias-{{ $index }}">Alias:</label> <input id="alias-{{ $index }}" type="text" [formControlName]="$index"> </div> } 您尝试在 Angular 17 中使用新的 @for 循环语法时似乎存在一些混乱。在 Angular 17 中循环遍历表单数组中的表单控件的正确语法如下: <div formArrayName="aliases"> <h2>Aliases</h2> <button type="button" (click)="addAlias()">+ Add another alias</button> <div *ngFor="let alias of aliases.controls; index as i"> <!-- The repeated alias template --> <label for="alias-{{ i }}">Alias:</label> <input id="alias-{{ i }}" type="text" [formControl]="alias"> </div> </div> 在更新的语法中,您使用 *ngFor 来迭代 aliases.controls 中的表单控件。 let alias 语法允许您在循环中引用当前表单控件,而 index as i 允许您获取索引。然后,您可以使用 [formControl]="alias" 将表单控件绑定到输入。 您尝试的 @for 语法对此用例无效。正确的 Angular 17 语法使用 *ngFor 指令以及当前项和索引的指定变量名称。在这种情况下不需要 trackBy 函数。

回答 2 投票 0

Angular 自定义表单控件与自定义验证器同步问题

实现 ControlValueAccessor 和 Validator 接口的自定义控件组件。 此自定义控件无法正确显示来自父组件验证器的错误。甚至家长组成...

回答 1 投票 0

递归嵌套形式数组角度

我定义了三种自定义类型,其中两种相互嵌套。 接口响应{ 标签:字符串; 问题:问题[]; } 界面问题{ 标签:字符串; 回复:回复...

回答 1 投票 0

Angular 8 在 2 个独立变量之间创建链接

我有一个数组,它根据其中的对象创建视图。可以使用 ngModel 更改对象内部的值。发生的情况是,当我得到数组的响应时,我设置了相同的分辨率...

回答 1 投票 0

如何检测ngModel是否脏了?

我有一个屏幕,其中输入字段根据 API 响应动态填充。每个输入字段都有一组与其关联的按钮。我想仅在字段...

回答 2 投票 0

如何在不触发valueChanges的情况下触发Angular FormControl验证?

我很好奇是否有人找到了一种无需使用即可触发验证的方法 updateValueAndValidity() (根据文档,它还会触发 FormControl 上的 valueChanges,这并不总是设计...

回答 2 投票 0

Angular 使用 ReactiveForms 验证 ControlValueAccessor

我使用 ControlValueAccessor 在 Angular 中创建自定义输入。我发现 FormControls 的验证停止工作。 这是我在 Stackblitz 上制作的一个简单示例。 @组件...

回答 1 投票 0

Angular 14:带有布尔值和默认值的类型化 FormControls

我尝试以下方法 new FormControl({ value: true }, Validators.required), 并得到错误,表示不存在布尔值的重载。使用 新的表单控件 我尝试以下方法 new FormControl<boolean | undefined>({ value: true }, Validators.required), 并得到错误:不存在 overloads 的 boolean 。使用 new FormControl<string | null>({ value: null, disabled: false })); 有效 ==> 那么,Angular 14 中 boolean 的类型化 FormControls 的正确语法是什么? 您可以像下面这样定义它: new FormControl<boolean>(true, Validators.required); 您可以将选项传递给它,如下所示: new FormControl<boolean>(true, { updateOn: 'submit', nonNullable: true, validators: Validators.required, }); 在此处阅读有关 Angular 14 类型化表单的更多信息:https://angular.io/guide/typed-forms#specifying-an-explicit-type

回答 1 投票 0

我如何知道自定义表单控件何时在 Angular 中被标记为原始?

我的 Angular 应用程序中有几个自定义表单控件组件,它们实现了 ControlValueAccessor 接口,并且效果很好。 然而,当在父窗体上调用 markAsPristine() 时,...

回答 5 投票 0

如何过滤FormGroup值?

我有一个巨大的FormGroup,它有很多FormControl和很多嵌套的FormArray,我需要获取顶部FormGroup除了一些控件之外的值。这些控件可能位于...

回答 1 投票 0

角度表单提交未提交

请帮助我的角度表单(提交)不起作用。我正在制作一个登录应用程序 登录.component.html 请帮助我的角度表单(提交)不起作用。我正在制作一个登录应用程序 登录.component.html <form (submit)="loginUser($event)"> <input type="text" placeholder="Enter Username"> <input type="password" placeholder="Enter Password"> <input type="submit" value="Submit"> </form> 登录.组件.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { constructor() { } ngOnInit() { } loginUser(event) { event.preventDefault() Console.log(event) } } 我建议您对 ReactiveForms 等表单使用角度组件: import { FormGroup, FormControl, Validators } from '@angular/forms'; public loginForm: FormGroup; constructor() { this.loginForm = new FormGroup({ 'username': new FormControl('', [ Validators.required ]), 'password': new FormControl('', [ Validators.required ]) }); } public sendLogin(): void { console.log(loginForm.value); } <form [formGroup]="loginForm" (ngSubmit)="loginForm.valid && sendLogin()"> <input formControlName="username" type="text" placeholder="Enter Username"> <input formControlName="password" type="password" placeholder="Enter Password"> <input type="submit" value="Submit"> </form> 请记住将 import { FormsModule, ReactiveFormsModule } from '@angular/forms'; 导入到您的 app.module.ts! 您需要做两件事才能工作。 1. 如果输入中没有 name 属性,Angular 表单将无法工作。 您可以按如下方式更改代码。 <input type="text" name="username" placeholder="Enter Username"> 然而,这并不特定于 Angular,而是一般的 HTML。 名称属性请参阅 MDN 描述 您还需要确保FormsModule已导入到您的角度模块中(最有可能是app.module.ts)。然后在表单标签中 Angular 包含 2 种管理表单的方法 - FormsModule 和 ReactiveFormsModule。 FormsModule 是两者中更容易的一个,但不能提供很多控制。 ReactiveFormsModule 有点复杂,但提供了很多控制。 对于你的情况FormsModule看起来已经足够好了。 此外,创建按钮的更语义化的方式是使用 <button type="submit>" 标签而不是 <input type="submit">。 你能试试这个吗?请使用 ngSubmit 而不是使用 (submit)。 <form (ngSubmit)="loginUser($event)"> 您可能需要在此处添加分号来美化您的代码 event.preventDefault(); Console.log(event); 这里有一些参考: https://angular.io/guide/forms Angular 在我们的应用程序中主要提供两种不同的构建表单的方式。他们是 : 1. 模板驱动方法,允许使用更少的 cpde 构建表单 2. 使用低级 API 的响应式方法,使我们的表单无需 DOM 即可测试。我们还可以使用 FormBuilder,它是一个高级 API,我们可以通过 Angular 访问。 如果你想使用模板驱动的方法。您需要首先在 app.module.ts 文件中导入 FormsModule。在文件中添加以下语句: 从'@angular/forms'导入{FormsModule}; 并在您的 @NgModule 指令中添加 FormsModule; @NgModule({ imports:[ //other imports FormsModule ], }) 然后在您的登录模板中,您需要进行更改,代码应如下所示: <form (ngSubmit)="loginUser($event)"> <input type="text" placeholder="Enter Username" id="username"> <input type="password" placeholder="Enter Password" id="password"> <button type="submit">Submit</button> <form> // 语义化并使用按钮而不是输入 type = "submit" 是件好事 并在login.component.ts中删除event.preventDefault()。而且,console.log 的语法带有小写“c”。所以,代码看起来像这样: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { constructor() { } ngOnInit() { } loginUser(event) { console.log(event); } } //您不需要添加 event.preventDefault(),因为您不会被重定向到任何新 URL。 现在您可以在控制台中看到您的事件正在被记录。 如果您想尝试反应式方法(也称为模型驱动)。您将需要导入 ReactiveFormsModule。因此,将以下代码片段添加到 app.mopdule.ts import { ReactiveFormsModule } from '@angular/forms' @NgModule({ imports:[ //other imports ReactiveFormsModule ], }) 请记住,响应式方法意味着您需要事先对表单进行建模并在模板中实现。 所以,在你的login.component.ts中。您将需要导入 FormControl 来设置表单的初始值。您的 login.component.ts 文件将如下所示: import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl } from '@angular/forms'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { loginForm = new FormGroup({ username: new FormControl(''), password: new FormControl('') }); constructor() { } ngOnInit() { } loginUser() { console.log(this.loginForm.value); } } 现在,将您的 login.component.html 文件更改为以下内容: <form [formGroup]="loginForm" (ngSubmit)="loginUser()"> <input type="text" placeholder="Enter Username" formControlName="username"> <input type="password" placeholder="Enter Password" formControlName="password"> <button type="submit">Submit</button> </form> 现在您可以看到控制台来查看正在存储的值。

回答 4 投票 0

src/app/reactive-form/reactive-form.component.html:47:48 - 错误 TS2531:对象可能为“null”。 src/app/reactive-form/reactive-form.component.ts

对象可能为“空”。元素隐式具有“any”类型,因为类型“controls”的表达式不能用于索引类型“AbstractControl”。 属性“控制”...

回答 1 投票 0

如何将 Api 中的值绑定到 Angular 表单

我创建了一个角度表单,它将值发送到 webapi 并在提交时在表单下方打印收到的值。 Try.component.html: 我创建了一个角度表单,它将值发送到 webapi 并在提交时在表单下方打印收到的值。 尝试.component.html: <div class="container"> <form [formGroup]="form" (submit)="onSubmit()" class="mb-3"> <!-- <form class="mb-3"> --> <div class="mb-3" class="row"> <label for="bike" class="form-label fw-bold">Bike:</label> <input type="text" class="form-control" id="bike" formControlName="bike" placeholder="Enter your Bike name"> </div> <button type="submit" class="btn btn-primary mr-1">Submit</button> </form> <br> <br> <div class="table-responsive"> <table class="table table-bordered" role="grid"> <thead class="bg-primary"> <tr> <th>Bike Name</th> </tr> </thead> <tbody> <tr *ngFor="let name of names"> <td> <input type="text" [(ngModel)]="name.bike" name="bike"> </td> </tr> </tbody> </table> </div> </div> 尝试.component.ts: export class TryComponent { names: any[] = []; form: FormGroup; constructor(private fb: FormBuilder, private namesService: NamesService) { this.form = this.fb.group({ bike: ['', [Validators.required, Validators.minLength(3)]] }); this.namesService.getBikes(); } Reset(){ this.form.reset(); } onSubmit() { this.form.controls['bike'].markAsTouched(); if (this.form.valid) { const data={ ...this.form.value, } console.log(data); this.namesService.addBike(data).subscribe(response => { console.log(response); this.namesService.getBikes().subscribe(names => { this.names = names; console.log(this.names); console.log("success"); }); }); } } } 名称.service.ts: export class NamesService { constructor(private http: HttpClient) { } addBike(nameData : any): Observable<any>{ return this.http.post<any[]>('https://localhost:7006/api/Names/submit-form',nameData); } getBikes(): Observable<any[]> { return this.http.get<any[]>('https://localhost:7006/api/Names/get-form-data'); } } 问题不在于 API,因为我可以在控制台上将输入的值作为数组打印(使用 swagger 测试时效果很好)。即使在导入必要的模块后,我也无法绑定该值和将其显示在表单下方。我想问题在于数组没有用前端接收到的值或我绑定的方式更新。 有人可以告诉我我哪里出了问题吗? 按如下方式修改您的TryComponent: import { Component, OnInit } from '@angular/core'; // Import OnInit // ... other imports ... export class TryComponent implements OnInit { // Implement OnInit names: any[] = []; form: FormGroup; constructor(private fb: FormBuilder, private namesService: NamesService) { this.form = this.fb.group({ bike: ['', [Validators.required, Validators.minLength(3)] }); } ngOnInit() { this.namesService.getBikes().subscribe(names => { this.names = names; }); } // ... rest of your component code ... } 通过实现 OnInit,您可以确保在初始化组件时进行 getBikes() 调用。 在 names 方法中成功添加自行车后,请务必更新 onSubmit() 数组: onSubmit() { this.form.controls['bike'].markAsTouched(); if (this.form.valid) { const data = { ...this.form.value, }; this.namesService.addBike(data).subscribe(response => { console.log(response); this.namesService.getBikes().subscribe(names => { this.names = names; // Update the names array console.log(this.names); console.log("success"); }); }); } }

回答 1 投票 0

如何将表单作为 Angular 组件输入传递?

在 Angular 16 应用程序中,我有一个模板驱动的表单,它将直接包含一个文本字段和我的提交按钮。它还包含一个组件,其中包含一些常见的可重用表单字段,所以...

回答 1 投票 0

如何使用 [ngModelOptions]="{standalone: true }" 检测模板驱动的表单更改

我正在尝试检测模板驱动表单中的更改,但它会抛出错误,因为 NgModel 未使用独立属性。 添加时忽略值变化 this.ngForm...

回答 1 投票 0

角度材质插入垫提示自定义表单控件

我有这个自定义 FormControl,它包含复杂的逻辑并使用 mat-form-field。 导出类 ComplexFormControlComponent 实现 ControlValueAccessor{ 私有 formControl = 新 FormC...

回答 3 投票 0

Angular 版本:14.2.9 - “表单数据绑定问题:数据未正确绑定/填充 - 需要帮助”

我目前正在使用 Angular 版本 14.2.9,在将数据绑定到表单时遇到问题。我想实现一个功能,在单击“更新”图标时,模式会打开...

回答 1 投票 0

Angular Stepper - addControl 和验证器的问题

我目前正在 Angular 中开发一个步进器。当我在子组件中导入的 formControl 上使用 addControl 时,我面临着挑战。当我添加的控件具有验证器时,

回答 1 投票 0

Angular updateValueAndValidity() 不起作用

我有简单的形式: 我有简单的形式: <form [formGroup]="form" (ngSubmit)="onSubmit()" novalidate> <input type="radio" id="enabled" formControlName="enabled" [value]="true" [checked]="form.controls.enabled.value == true" (click)="setValidators()"> <label for="enabled">Enable</label> <input type="radio" id="disabled" formControlName="enabled" [value]="false" [checked]="form.controls.enabled.value == false" (click)="clearValidators()"> <label for="disabled">Disable</label> <input type="text" class="form-control" id="text" formControlName="text"> <button type="submit" [disabled]="!form.valid">Save Changes</button> </form> 和角度分量代码: ngOnInit() { this.buildForm(); } buildForm() { this.form = this.formBuilder.group({ text: [''], enabled: [false] }); } clearValidators() { this.form.get("text").clearValidators(); this.form.updateValueAndValidity(); } setValidators() { this.form.get("text").setValidators([Validators.required]); this.form.updateValueAndValidity(); } 当我加载页面时,我有 enabled = false 和 text='',但是当我单击“启用”单选按钮时,我希望在 text 字段上设置验证器,但 text='' 和 form 应该无效,并且提交按钮将是无效的禁用。但是当我在浏览器控制台中输出 form.valid value = true 并且我期望 false. 我做错了什么?我该如何解决这个问题? 我认为 updateValueAndValidity 不会传播到子元素。您还必须在表单控件上调用它: this.form.get("text").updateValueAndValidity()

回答 1 投票 0

formBuilder中我们应该如何输入控件?

我们应该如何在formBuilder中输入控件 - 我一直在寻找答案,到目前为止还没有答案,问题是这样的 我们创建一个接口: 界面 myForm { 名称:字符串; 年龄:数字...

回答 1 投票 0

© www.soinside.com 2019 - 2024. All rights reserved.