angular-reactive-forms 相关问题

关于角度反应形式的问题,一种用于以反应式方式创建表格的角度技术。将此标记用于不是特定于单个Angular版本的问题。

如何在 Angular 17 中创建响应式表单

我有这个HTML代码: ... 我有这个 HTML 代码: <form (ngSubmit)="onSubmit()"> <div class="row gy-3"> <div class="col-lg-6"> <label class="form-label text-sm text-upperc ase" [(ngModel)]="firstName" name="firstName">Ime</label> <input class="form-control form-control-lg" type="text" id="firstName" placeholder="Unesite svoje ime"> </div> <div class="col-lg-6"> <label class="form-label text-sm text-uppercase" [(ngModel)]="lastName" name="lastName">Prezime</label> <input class="form-control form-control-lg" type="text" id="lastName" placeholder="Unesite svoje prezime"> </div> <div class="col-lg-6"> <label class="form-label text-sm text-uppercase" [(ngModel)]="email" name="email">Email</label> <input class="form-control form-control-lg" type="email" id="email" placeholder="e.g. [email protected]"> </div> <div class="col-lg-6"> <label class="form-label text-sm text-uppercase" >Broj telefona</label> <input class="form-control form-control-lg" type="tel" id="phone" placeholder="e.g. +381 6665544"[(ngModel)]="phoneNumber" name="phoneNumber"> </div> <div class="col-lg-6"> <label class="form-label text-sm text-uppercase" >Ime kompanije(opciono) </label> <input class="form-control form-control-lg" type="text" id="company" placeholder="Ime kompanije"[(ngModel)]="companyName" name="companyName"> </div> <div class="col-lg-12"> <label class="form-label text-sm text-uppercase" >Adresa 1</label> <input class="form-control form-control-lg" type="text" id="address" placeholder="Postanski broj,ulica i broj"[(ngModel)]="address1" name="address1"> </div> <div class="col-lg-12"> <label class="form-label text-sm text-uppercase" >Adresa 2</label> <input class="form-control form-control-lg" type="text" id="addressalt" placeholder="Sprat,zgrada,ulaz"[(ngModel)]="address2" name="address2"> </div> <div class="col-lg-6"> <label class="form-label text-sm text-uppercase" >Grad</label> <input class="form-control form-control-lg" type="text" id="city"[(ngModel)]="city" name="city"placeholder="Unesite grad"> </div> <div class="col-lg-6"> <label class="form-label text-sm text-uppercase" >Drzava</label> <input class="form-control form-control-lg" type="text" id="state" [(ngModel)]="state" name="state"placeholder="Unesite drzavu"> </div> <div class="col-lg-12 form-group"> <button class="btn btn-success" type="submit">Porucite</button> </div> </div> </form> 这是我的checkout.component.ts: import { Component, OnInit } from '@angular/core'; import { FormGroup, FormsModule } from '@angular/forms'; import { Order } from '../models/order.model'; @Component({ selector: 'app-checkout', standalone: true, imports: [FormsModule], templateUrl: './checkout.component.html', styleUrl: './checkout.component.css', }) export class CheckoutComponent implements OnInit{ billingFormGroup!:FormGroup order:Order = new Order() firstName!:string lastName!:string email!:string phoneNumber!:string companyName!:string address1!:string address2!:string city!:string state!:string constructor(){ } onSubmit() { this.order.firstName=this.firstName this.order.lastName=this.lastName this.order.email=this.email this.order.phoneNumber=this.phoneNumber if(this.companyName)this.order.companyName=this.companyName if(this.address1)this.order.address=this.address1 if(this.address2)this.order.optionalAddress=this.address2 this.order.town=this.city this.order.state=this.state // this.order.firstName=this.billingFormGroup.get('firstName')?.value; // this.order.lastName=this.billingFormGroup.get('lastName')?.value; // this.order.email=this.billingFormGroup.get('email')?.value; // this.order.phoneNumber=this.billingFormGroup.get('phoneNumber')?.value; // if(this.billingFormGroup.get('companyName')?.value != null)this.order.companyName=this.billingFormGroup.get('companyName')?.value; // if(this.billingFormGroup.get('address1')?.value != null)this.order.address=this.billingFormGroup.get('address1')?.value; // if(this.billingFormGroup.get('address2')?.value != null)this.order.optionalAddress=this.billingFormGroup.get('address2')?.value; // this.order.town=this.billingFormGroup.get('city')?.value; // this.order.state=this.billingFormGroup.get('state')?.value; console.log(this.order) } ngOnInit(): void { // this.billingFormGroup=new FormGroup({ // 'firstName':new FormControl('',[Validators.required]), // 'lastName':new FormControl('',[Validators.required]), // 'email':new FormControl('',[Validators.email]), // 'phoneNumber':new FormControl('',[Validators.required]), // 'companyName':new FormControl(''), // 'address1':new FormControl('',[Validators.required]), // 'address2':new FormControl(''), // 'city':new FormControl('',[Validators.required]), // 'state':new FormControl('',[Validators.required]) // }) } } 注释的代码向我抛出错误。此外,未注释的代码在控制台中向我抛出相同的错误: 错误错误:NG01203:没有表单控件名称的值访问器:'firstName'。欲了解更多信息,请访问 https://angular.io/errors/NG01203 我读过一些关于 ControlValueAccessor 的内容,但我不知道如何实现它。 有人能解释一下为什么 Angular 会抛出这个错误吗?这是 Angular 17 中添加的新功能还是其他东西,因为在以前的版本中我没有遇到任何表单问题? 您无法将 ngModel 绑定到标签。由于标签不提供任何控制值 从;中删除[(ngModel)]="firstName" <label class="form-label text-sm text-upperc ase" [(ngModel)]="firstName" name="firstName">Ime</label>

回答 1 投票 0

如何在 Angular 中对静态 JSON 数组执行 CRUD 操作? (无API)

我有这个 JSON 数组文件。 [ { “id”:1, “姓名”:“约翰·多伊”, “电子邮件”:“[email protected]”, “年龄”:25 ...

回答 1 投票 0

如何在多参数 JSON 数组中执行获取、更新、添加和删除操作,就像 Angular 中的 API 一样

我有这个多参数 JSON 数组: 公开课程列表:任意=[ { 编号:1, cName:“角度”, bDesc: "这是 Angular 的基础课程。", 一个...

回答 1 投票 0

带有行为主题的角度反应式表单验证

黑社区, 我想知道当存在一些相互依赖的动态字段并且需要调用 API 进行验证时,验证 Angular Reactive Forms 的最佳方法是什么。 我有一个输入,A

回答 1 投票 0

结合 HTML 和 Angular 反应式表单验证

我正在构建一个 Angular Reactive Form,并且我有一个数字类型的输入。我已向 FormControl 提供了 Validators.min(0),但是当我聚焦输入并向下滚动或按住箭头时

回答 1 投票 0

无法使用 Angular Reactive Forms 将选择选项的值设置为 ngFor 循环中的第一个元素

我有一个带有 ngFor 循环的选择输入,用于根据颜色数组创建选项。 我需要的行为是自动选择第一个选项,以便角度反应形式可以......

回答 1 投票 0

Angular - 自定义验证器不使用组件变量的最新值

我有以下在 ngOnInit 中创建的表单组: 私人 setScreeningStatusForm(screeningStatusData: ClientScreeningStatusModel | 未定义): void { this.screeningStatusForm = ...

回答 1 投票 0

是否有一个带有 Angular 反应形式和 matInput 的简单数字输入?

如何拥有具有反应形式的? 没有原生的数字验证器(https://angular.io/api/forms/Validators),但你可以轻松地做一个模式 Validators.pa...

回答 2 投票 0

如何取消选择垫选中的“全选”选项

我正在使用 Angular 15,并使用“全选”选项创建此多重选择垫选择下拉列表: 选择周一...

回答 1 投票 0

在反应式表单控件中与 Validators.required 一起使用的自定义控件不显示指示器

假设我们有 2 个输入:MatInput 控件和自定义输入控件。 电话号码 < 假设我们有 2 个输入:MatInput 控件和自定义输入控件。 <div [formGroup]="form"> <mat-form-field> <mat-label>Phone number</mat-label> <example-tel-input formControlName="tel"></example-tel-input> <mat-icon matSuffix>phone</mat-icon> <mat-hint>Include area code</mat-hint> </mat-form-field> <mat-form-field> <mat-label>Mobile number</mat-label> <input type="text" matInput formControlName="mobile" /> </mat-form-field> </div> 如果我们迫切需要这两个组件: form: FormGroup = new FormGroup({ tel: new FormControl(null, [Validators.required]), mobile: new FormControl(null, [Validators.required]), }); 手机显示指示符 (*),而电话则不显示。在文档中它说: 请注意,必需的属性仍然存在于模板中。 虽然对于验证来说不是必需的,但应该保留它 可访问性目的。 这意味着对于自定义组件,我需要在 HTML 模板中包含 required。 <example-tel-input formControlName="tel" required></example-tel-input> 我想知道为什么会这样。 这是重复的代码。 MatInput如何访问父类中需要的验证器而自定义控件却不能? 这是Stackblitz。 在对 MatInput 进行一些帮助和调查之后,有人建议我能够通过 ngControl 访问验证器。 在自定义组件类构造函数中已经有: @Optional() @Self() public ngControl: NgControl 那么不需要有默认的 _required 值(未定义): private _required: boolean | undefined; @Input() get required(): boolean { return ( this._required ?? this.ngControl?.control?.hasValidator(Validators.required) ?? false ); }

回答 1 投票 0

如何为角度过滤器制作依赖的另一个下拉列表

如何使 Angular 中的过滤器依赖另一个下拉菜单。我有多个下拉菜单,它们相互依赖。我正在使用反应形式。 如何在角度中为过滤器建立依赖的另一个下拉菜单。我有多个下拉菜单,它们相互依赖。我正在使用反应形式。 <select (change)="checkFirstDropdown()" formControlName="id" class="FormControl cond-size"> <option value="null" disabled >Please Select Option</option> <option [ngValue]="noneDropDown" selected> none </option> <ng-container *ngIf="checkMainIndex==0"> <ng-container *ngFor="let conditionsOperatorElement of allObjects.conditionsOperator"> <option *ngIf="conditionsOperatorElement.conditionsOperatorId==1" [ngValue]="conditionsOperatorElement.conditionsOperatorId" >{{ conditionsOperatorElement.title }}</option> </ng-container> </ng-container> <ng-container *ngIf="checkMainIndex!=0"> <option [ngValue]="conditionsOperatorElement.conditionsOperatorId" *ngFor="let conditionsOperatorElement of allObjects.conditionsOperator">{{ conditionsOperatorElement.title }}</option> </ng-container> </select> 我想我有一个解决方案给你。您可以在 change 函数上执行此操作。 这是我的示例代码和 stackblitz 演示链接。 HTML: <h1>Reactive forms SELECT-OPTIONS</h1> <h2>Tracking simple string</h2> <form [formGroup]="form"> <label>Country:</label><br> <select formControlName="country" (change)="checkFirstDropdown($event.target.value)"> <option *ngFor="let country of countries" [value]="country.id"> {{ country.name }} </option> </select> <br> <br> <label>City</label><br> <select formControlName="city" > <option *ngFor="let city of cities" [value]="city.id"> {{ city.city }} </option> </select> </form> TS: import { Component } from '@angular/core'; import { FormGroup, FormControl } from '@angular/forms'; import {Country} from './country'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { countries = [ { id: 'us', name: 'United States' }, { id: 'uk', name: 'United Kingdom' }, { id: 'ca', name: 'Canada' } ]; cities=[]; form = new FormGroup({ country: new FormControl(), city: new FormControl() }); checkFirstDropdown($event){ this.cities=cityList.filter(c=>c.cid===$event); let itm=this.cities[0]; this.form.controls['city'].setValue(itm.id); console.log($event); } } export const cityList = [ { id: "1", cid: 'ca', city: "toronto", }, { id: "2", cid: 'ca', city: "Vancouver", }, { id: "3", cid: 'us', city: "New York City", }, { id: "4", cid: 'us', city: "Los Angeles", }, { id: "5", cid: 'uk', city: "London", }, { id: "6", cid: 'uk', city: "BRIGHTON", } ]; **HTML**: <div class="row mt-3"> <div class="col-3"> <label for="">Select Category</label> <select class="form-control" [(ngModel)]="selectedCategory" (change)="onCategoryChange()" (change)="checkFirstDropdown(selectedCategory)"> <option value="">Select</option> <option *ngFor="let category of categories" [value]="category"> {{category}}</option> </select> </div> <div class="col-3"> <label for="">Select Product</label> <select class="form-control" [(ngModel)]="products"> <option value="">Select</option> <option *ngFor="let product of products" [value]="product"> {{product.name}}</option> </select> </div> <div class="Container"> <app-my-table></app-my-table> </div> </div> **TS**: import { Component, OnInit } from '@angular/core'; import { ProductService } from '../product.service'; import { Product } from '../product'; @Component({ selector: 'app-pos', templateUrl: './pos.component.html', styleUrls: ['./pos.component.css'] }) export class POSComponent implements OnInit { categories: string[] = []; products: Product[] = []; selectedCategory: string = ''; selectedCategoryProducts: any[] = []; constructor(private productService: ProductService) { } ngOnInit() { //it loads your first dropdown data this.loadData(); } loadData() { this.productService.getCategoriesOnly().subscribe((category: any) => { this.categories = category.data; }) } //checks first dropdown value checkFirstDropdown(selectedCategory: string) { this.selectedCategoryProducts = this.products.filter(c => c.category === selectedCategory); if (selectedCategory != null || selectedCategory != "Select") { this.getProductByCategory(selectedCategory); } } // its an api call in service which gets data for 2nd list getProductByCategory(category: string) { this.productService.getProductByCategory(category).subscribe((product: any) => { this.products = product.data; }) } // on changing category first it will empty the array of products onCategoryChange() { this.products = []; // Reset selected product when category changes } } }

回答 0 投票 0

Angular - 反应式表单:在 FormArray 中使用 FormGroup 的正确方法

在 Angular 中创建 FormGroup 的 FormArray 的正确方法是什么? 我有以下内容: 组件.ts: 导出类 DrawerContentComponent 实现 OnInit { 消耗 = 新的 FormGroup({

回答 1 投票 0

如何使用 Angular 4 Reactive Form 在 PrimeNg MultiSelect 中设置默认选定值?

我正在使用 PrimeNg (PrimeNg Multiselect) 和 Angular4 的 MultiSelect 控件与反应式表单,并且我想在表单加载期间保留一些默认选择的项目。 超文本标记语言 我正在将 PrimeNg (PrimeNg Multiselect) 和 Angular4 的 MultiSelect 控件与反应式表单一起使用,并且我想在表单加载期间保留一些默认选择的项目。 HTML <div class="col-md-4"> <span translate>settings.account.webhook.label.additional.variables</span> <p-multiSelect [options]="sensorsList" (onChange)="changeSensorsList($event)" formControlName="selectedSensorsList" name="selectedSensorsList" [panelStyle]="{minWidth:'20em'}"></p-multiSelect> </div> 这是我的 TypeScript 代码 sensorsList = [ { label: 'lat', value: {'id': 0, 'itemName': 'lat', 'selected': false }}, { label: 'lng', value: {'id': 1, 'itemName': 'lng' , 'selected': false}}, { label: 'address', value: {'id': 2, 'itemName': 'address' , 'selected': false}}, { label: 'origin', value: {'id': 3, 'itemName': 'origin' , 'selected': false}} ]; this.addEditWebhookForm = this._formBuilder.group({ name: [(_webhookToEdit) ? _webhookToEdit['name'] : '', [Validators.required]], selectedSensorsList: [] }); 当您创建selectedSensorsList时,您需要为您的formGroup提供价值: this.addEditWebhookForm = this._formBuilder.group({ ..., selectedSensorsList: [ defaulSensorsList ] }); 或稍后设置该值: this._formBuilder.get('selectedSensorsList').setValue(defaultSenorsList); HTML 您需要在 primeng 组件中设置一个 ngModel <div class="col-md-4"> <span translate>settings.account.webhook.label.additional.variables</span> <p-multiSelect [options]="sensorsList" (onChange)="changeSensorsList($event)" formControlName="selectedSensorsList" name="selectedSensorsList" [panelStyle]="{minWidth:'20em'}" [(ngModel)]="selectedDefault"></p-multiSelect> </div> TS selectedDefault= []; sensorsList.map((item) => selectedDefault.push(item.value)); 在这里我选择了所有这些。 您还必须更新传感器列表对象以将所选值更改为 true 你必须在 ngOnInit 中设置默认选项 selectedSensorsList: [{'id': 0, 'itemName': 'lat'}]

回答 3 投票 0

如何过滤fromgroup中的下拉列表?

HTML 文件 HTML 文件 <div formGroupName="ISOReportForm"> <div [formGroup]="sensitivityReportForm"> <div *ngFor="let item of formArray; let i = index" formArrayName="items"> <div formGroupName="{{i}}"> <div class="d-flex justify-content-between"> <h5 class="sensiHeading">Sensitivity analysis {{i + 1}}</h5> <span class="sensiHeading" *ngIf="i != 0" role="button" (click)="removeSensitivityItem(i)"> Remove</span> </div> <div class="row scenarios-div ng-select-div reportGenerationDrd"> <div class="col-12"> <ng-select [clearable]="true" [clearOnBackspace]="false" #addRedefrences [items]="baselineScenarioList" [searchable]="false" bindLabel="name" [formControlName]="'addRefrences'" bindValue="idStr" [searchFn]="commonInputSearchName" [multiple]="false" placeholder="Add reference for sensitivity analysis" (change)="selectAddRefrences($event,i)" (clear)="resetCalculations(i)"> <ng-template ng-header-tmp> <div class="has-feedback"> <input placeholder="Search..." (input)="addRedefrences.filter($any($event.target).value)" type="text" class="form-control search-input" id="inputValidation" /> <span class="form-control-feedback"> <i class="fa fa-search icon"></i> </span> </div> </ng-template> <ng-template ng-option-tmp let-item="item" let-search="searchTerm"> <div [ngOptionHighlight]="search" title="{{item?.name}}">{{ item.name }}</div> </ng-template> </ng-select> </div> </div> <div class="row scenarios-div ng-select-div reportGenerationDrd"> <div class="col-12 col-md-6"> <ng-select [clearable]="true" [clearOnBackspace]="false" #Variation1 [formControlName]="'variationOne'" [items]="variationLists" [searchable]="false" bindLabel="name" [searchFn]="commonInputSearchName" bindValue="idStr" [multiple]="false" placeholder="Variation 1"> <ng-template ng-header-tmp> <div class="has-feedback"> <input placeholder="Search..." (input)="Variation1.filter($any($event.target).value)" type="text" class="form-control search-input" id="inputValidation" /> <span class="form-control-feedback"> <i class="fa fa-search icon"></i> </span> </div> </ng-template> <ng-template ng-option-tmp let-item="item" let-search="searchTerm"> <div [ngOptionHighlight]="search" title="{{item?.name}}">{{ item.name }}</div> </ng-template> </ng-select> </div> <div class="col-12 col-md-6 reportGenerationDrd"> <ng-select [clearable]="true" [clearOnBackspace]="false" #Variation2 [formControlName]="'variationTwo'" [items]="variationLists" [searchable]="false" bindLabel="name" [searchFn]="commonInputSearchName" bindValue="idStr" [multiple]="false" placeholder="Variation 2"> <ng-template ng-header-tmp> <div class="has-feedback"> <input placeholder="Search..." (input)="Variation2.filter($any($event.target).value)" type="text" class="form-control search-input" id="inputValidation" /> <span class="form-control-feedback"> <i class="fa fa-search icon"></i> </span> </div> </ng-template> <ng-template ng-option-tmp let-item="item" let-search="searchTerm"> <div [ngOptionHighlight]="search" title="{{item?.name}}"> {{ item?.name }} </div> </ng-template> </ng-select> </div> </div> <div class="row scenarios-div ng-select-div reportGenerationDrd"> <div class="col-12 col-md-6"> <ng-select [clearable]="true" [clearOnBackspace]="false" #Variation3 [formControlName]="'variationThree'" [items]="variationLists" [searchable]="false" bindLabel="name" [searchFn]="commonInputSearchName" bindValue="idStr" [multiple]="false" placeholder="Variation 3"> <ng-template ng-header-tmp> <div class="has-feedback"> <input placeholder="Search..." (input)="Variation3.filter($any($event.target).value)" type="text" class="form-control search-input" id="inputValidation" /> <span class="form-control-feedback"> <i class="fa fa-search icon"></i> </span> </div> </ng-template> <ng-template ng-option-tmp let-item="item" let-search="searchTerm"> <div [ngOptionHighlight]="search" title="{{item?.name}}">{{ item.name }}</div> </ng-template> </ng-select> </div> <div class="col-12 col-md-6 reportGenerationDrd"> <ng-select [clearable]="true" [clearOnBackspace]="false" #Variation4 [formControlName]="'variationFour'" [items]="variationLists" [searchable]="false" bindLabel="name" [searchFn]="commonInputSearchName" bindValue="idStr" [multiple]="false" placeholder="Variation 4"> <ng-template ng-header-tmp> <div class="has-feedback"> <input placeholder="Search..." (input)="Variation4.filter($any($event.target).value)" type="text" class="form-control search-input" id="inputValidation" /> <span class="form-control-feedback"> <i class="fa fa-search icon"></i> </span> </div> </ng-template> <ng-template ng-option-tmp let-item="item" let-search="searchTerm"> <div [ngOptionHighlight]="search" title="{{item?.name}}"> {{ item?.name }} </div> </ng-template> </ng-select> </div> </div> </div> </div> <button class="blue-hoki-add" type="button " id="btnmanufacturingprocessofmaterial " (click)="addItem()" (mouseenter)=" changeImageOnHover(true)" (mouseleave)=" changeImageOnHover(false)"><img class="fa fa-plus" width="60" height="60" [src]="isHovered ? './assets/icons/add-record-hover.svg': './assets/icons/add-record.svg'"></button> <hr class="hr"> </div> </div> TS 文件 get formArray() { return (this.sensitivityReportForm.get('items') as FormArray).controls; } ngOnInit(): void { this.formGroupRenderer(); } formGroupRenderer() { this.reportChartForm = this.formBuilder.group({ // input reportTitle: [null], // checkbox excludeProductImpacts: [false, Validators.required], includeInputInformation: [false, Validators.required], // dropdowns // reportFormat: [null, Validators.required], newFormateList: [null, Validators.required], reportFormatByList: [null], includeScenario: [null, Validators.required], functionalUnit: [null, Validators.required], baselineScenario: [null, Validators.required], impactCategories: [null], includeCategories: [null], additionalInformation: [null], ISOReportForm: this.formBuilder.group({ reasonOfStudy: [null], criticalViewer: [null], organizationISO: [null], viewSysBoundry: [null], boundryJustification: [''], excludedProcessJusti: [''], impactCategoryJustification: [''], multiFunJustification: [''], otherAssumption: [''], conclusion: [''] }), }); this.sensitivityReportForm = this.formBuilder.group({ items: this.formBuilder.array([]) }); this.ISOReportForm = this.reportChartForm.controls['ISOReportForm']; this.ISOReportForm.get('organizationISO').disable(); this.addItem(); } addItem(itemData?: any) { const variaton = this.baselineScenarioList?.filter((x: any) => x.idStr != itemData?.referenceSystemAnalysis); this.variationLists = variaton; const itemFormGroup = this.formBuilder.group({ addRefrences: [itemData ? JSON.stringify(itemData.referenceSystemAnalysis) : null], variationOne: [itemData ? JSON.stringify(itemData.variationOne) : null], variationTwo: [itemData ? JSON.stringify(itemData.variationTwo) : null], variationThree: [itemData ? JSON.stringify(itemData.variationThree) : null], variationFour: [itemData ? JSON.stringify(itemData.variationFour) : null], }); const itemsArray = this.sensitivityReportForm.get('items') as FormArray; if (itemData) { // Update existing item if it exists const existingItem = itemsArray.controls.find(control => control.value.referenceSystemAnalysis === itemData.referenceSystemAnalysis); if (existingItem) { const existingItemIndex = itemsArray.controls.indexOf(existingItem); itemsArray.setControl(existingItemIndex, itemFormGroup); } else { // If not found, push a new item itemsArray.push(itemFormGroup); } } else { // If no itemData provided, add a new item itemsArray.push(itemFormGroup); } } selectAddRefrences(event: any, index: number) { const variaton = this.baselineScenarioList.filter((x: any) => x.idStr != event.idStr); this.variationLists = variaton; debugger const itemsArray = this.sensitivityReportForm.get('items') as FormArray; const item = itemsArray.at(index) as FormGroup | null; // Set values only for the specified item if (item) { item.controls['variationOne'].setValue(null); item.controls['variationTwo'].setValue(null); item.controls['variationThree'].setValue(null); item.controls['variationFour'].setValue(null); } } resetCalculations(index: number) { const itemsArray = this.sensitivityReportForm.get('items') as FormArray; for (let i = 0; i < itemsArray.length; i++) { const item = itemsArray.at(i) as FormGroup | null; // Access individual item as FormGroup or null item?.controls['variationOne'].setValue(null); item?.controls['variationTwo'].setValue(null); item?.controls['variationThree'].setValue(null); item?.controls['variationFour'].setValue(null); } } 现在我有五个 ng-select 下拉菜单。我需要绑定所有下拉列表 uniq 就像 如果选择了 addRefrence 下拉列表,则下面的四个 ng-select 列表不包含 addreferences 的选择值 现在选择变体一下拉列表,然后下面的三个ng-select列表不包含变体One的选择值 插入所有下拉列表 uniq 你能制作一个 stackblitz 运行你的代码的例子吗?

回答 1 投票 0

如何在不使用服务的情况下在子组件和父组件之间传递反应式表单数据

当我们单击父级按钮时,我们希望使用来自父级的子级反应式表单数据。目前我们正在使用 viewchild 来获取子组件引用。我们的一切都变得静态了......

回答 2 投票 0

实现 Angular 跨域验证的最佳方式

我正在尝试找出在 Angular 中实现跨字段验证的最佳方法。 例如,我有一个选择字段,该字段使另一个字段成为必填字段。 我希望能够: 改变b...

回答 3 投票 0

错误错误:找不到名称为reactiveForms Angular的控件

我正在尝试将数据插入数据库中的两个表:“客户”和“地址”。我想通过包含客户和地址字段的表单来完成此操作。这个想法是添加...

回答 1 投票 0

Angular 异步验证器在 formGroup.addControl/removeControl 上触发

我们有一个漂亮的嵌套反应式 Angular,其中所有 FormControl 都位于 FormArray 内的 FormGroup 内。一些 FormControl 具有异步验证器来检查唯一性......

回答 1 投票 0

模板错误类型“AbstractControl”无法分配给类型“FormControl”

为什么我会收到此错误? 以下代码在另一个应用程序中有效 为什么我会收到此错误? 以下代码适用于另一个应用程序 <input class="form-control form-control-sm" type="number" min="0" [formControl]='invoiceForm.get("quantity")'> 在这个新应用程序中它也可以工作,但仍然在终端中抱怨 Type 'AbstractControl' is not assignable to type 'FormControl'. <input type="password" placeholder="Confirm Password" class="form-control" [formControl]="$any(myForm).controls['confirmpassword']"/> 使用 $any 函数禁用类型检查。我用这个解决了我的错误。 如果其他人仍然遇到这个问题,我分享我的解决方案,它与Bellash描述的几乎相同,但性能更好。 对于这个例子: <input class="form-control form-control-sm" type="number" min="0" [formControl]='invoiceForm.get("quantity")' | formControl> 我们只需要创建并使用管道,它将返回正确类型的值 @Pipe({ name: 'formControl', }) export class FormControlPipe implements PipeTransform { transform(value: AbstractControl): FormControl<typeof value['value']> { return value as FormControl<typeof value['value']>; } } 通过这种方式,您将获得更好的性能,因为仅当提供的表单发生更改时才会调用管道转换函数。 通常在模板中使用函数是不好的做法,因为每个生命周期更改都会调用此函数,并且在较大的项目上会产生很大的性能问题。最好的方法是使用管道(通常正是为了此类目的而开发的),仅在渲染时转换某些值(仅当某些值需要更改时)。 希望这会对某人有所帮助) 如果您使用 Angular 9 或更高版本,此问题可能来自 tsconfig.json "angularCompilerOptions": { ... "strictTemplates": true <-- causing "Type 'AbstractControl' is not assignable to type 'FormControl'" } 第一个选项 通过设置"strictTemplates": false可能会暂时“解决”问题 第二个选项 通过模板将AbstractControl转换为FormControl,所以你的.ts文件应该有 convertToFormControl(absCtrl: AbstractControl | null): FormControl { const ctrl = absCtrl as FormControl; return ctrl; } 还有你的html <input type="text" [formControl]="convertToFormControl(invoiceForm.get("quantity"))" /> 从这个官方文档以及根据FormControl定义,我们可以看到FormControl继承自AbstractControl。由于 FormGroup.controls 和 FormGroup.get("key") 都返回 AbstractControl,我必须创建一个函数来从 Parent 类转换为 Child 类。 toControl(absCtrl: AbstractControl): FormControl { const ctrl = absCtrl as FormControl; // if(!ctrl) throw; return ctrl; } 和模板 <input class="form-control form-control-sm" type="number" min="0" [formControl]='toControl(invoiceForm.get("quantity"))'> PS:我无法使用FormControlName,因为我有很多表单组和子组/数组。那就是我必须使用banana in box指令,因为它的值是强类型的 编辑 2022:另请考虑下面的 @Avetik 答案,将此函数转换为管道以获得更好的性能 感谢 Avetik 和 Imo 提供我列出的大部分信息。以下步骤适用于 Angular 13+: 在基础项目文件夹中创建文件 form-control.pipe.ts: import {Pipe, PipeTransform} from '@angular/core'; import {AbstractControl, FormControl} from '@angular/forms'; @Pipe({ name: 'formControl', }) export class FormControlPipe implements PipeTransform { transform(value: AbstractControl): FormControl { return value as FormControl; } } 在项目的 @NgModule 的声明部分中,将 FormControlPipe 添加到列表中并导入它。 在任何地方收到此 lint 警告,请添加 | FormControl(包括管道符号) [formControl]="form.get('wordRuleForm').get('sound') | formControl" 问题解决了! 我有一个与formGroup类似的控件,所以我基于formGroup创建了一个类似的过滤器,它的使用方式如下: [commonForm]="form.get('commonForm') | formGroup" 我可以通过让模板直接访问 FormControl 并将其添加到 initForm() 中的表单来解决这个问题。 .ts form: FormGroup = new FormGroup({}); quantity: FormControl = new FormControl(Quantity.MIN, [ Validators.min(Quantity.MIN), Validators.max(Quantity.MAX), ]); ngOnInit(): void { this.initForm(); } initForm(): void { this.form.addControl('quantity', this.quantity); } .html(在我的例子中,我将 FormControl 数量传递给一个自定义组件,该组件采用名为“control”的 FormControl Input()。) <form [formGroup]="form" (ngSubmit)="submit()"> <app-select-quantity [control]="quantity"></app-select-quantity> <div> <button mat-flat-button type="submit" color="primary" [disabled]="!form.valid" > Submit </button> </div> </form> <input type="name" placeholder="Name" class="form-control" [formControl]="$any(cardForm).controls.name" /> 这里 $any 函数将禁用类型检查。 我并不是很热衷于使用解决方法(所有答案似乎都是如此),并且碰巧遇到了 Angular University 示例中使用的策略。 您可以通过将 get 属性公开给模板上的 formControlName 来轻松地将表单控件公开给表单: <input class="form-control form-control-sm" type="number" min="0" formControlName='quantity'> <!-- formControlName instead of [formControl] --> 在组件中: // The get property should match the formControlName above. get quantity() { return this.form.controls["quantity"]; } 这个 Angular 问题与切线相关,但很有趣 - 对于自定义类型的表单: (表单):类型化表单和泛型/继承的问题。 https://github.com/angular/angular/issues/47091 你可以试试 <input class="form-control form-control-sm" type="number" min="0" [formControl]='invoiceForm.controls.quantity'> 或者我个人最喜欢的处理表单的方式 <div [formGroup]="inviceForm"> <!-- any tag that wraps all of your controls --> <!-- some input before (anything)--> <input class="form-control form-control-sm" type="number" min="0" formControlName='quantity'> <!-- some inputs after (anything)--> </div> 如果存在不同版本或没有“类型”转换匹配,您可以使用“任何”作为临时解决方案。例如 来自: event: FormControl 致: event: any

回答 11 投票 0

FormArray 正在填充重复的控件

所以,我有一个列表组件,它在视图模板中有一个子组件。 它使用异步管道与可观察列表循环。 现在我介绍一个搜索控件,它可以过滤掉列表...

回答 1 投票 0

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