验证在formgroup中的Angular 13中的验证中断

发布于 2025-02-12 15:26:58 字数 5027 浏览 0 评论 0原文

我花了最后几个小时在Angular 13中填充了我的表格下拉菜单,最后我设法使其正常工作,尽管在代码中填充下拉列表并不是问题,但其他控件会破坏我的下拉序列:

例如:

@Component({
  selector: 'app-company-add',
  templateUrl: './company-add.component.html',
  styleUrls: ['./company-add.component.css']
})
export class CompanyAddComponent implements OnInit {

 currencies: Currency[] = [];

  form = new FormGroup({
    name: new FormControl('',[Validators.required]),     
    currency: new FormControl('', Validators.required),
    address: new FormGroup({
        street: new FormControl('',[Validators.required]),
        city: new FormControl('',[Validators.required]),
        country: new FormControl('',[Validators.required]),
    })
  });


  constructor( public companyService: CompanyService, public currencyService: CurrencyService,
    private router: Router) {

     }

  ngOnInit() {
    this.currencyService.getAll().subscribe((data: Currency[])=>{
      this.currencies = data;
      console.log(this.currencies);    
    })  
}

  get f(){
    return this.form.controls;
  }
  
  submit(){
    console.log(this.form.value);
    this.companyService.create(this.form.value).subscribe((res:any) => {
      console.log(res);
         console.log('Post created successfully!');
         this.router.navigateByUrl('details');
    })
  }
}

<form [formGroup]="form" (ngSubmit)="submit()">
<div class="row">

    <div class="col">
        <h2>Add new company</h2>
        <label for="name">Name:</label>
        <input formControlName="name" id="name" type="text" class="form-control" style="width: auto;">
        <div *ngIf="f['name'].touched && f['name'].invalid" class="alert alert-danger">Name is requiered.
            <div *ngIf="f['name'].errors && f['name'].errors['required']">Name is requiered.</div>
        </div>          

        <label for="currency">Currency:</label>
        <select formControlName="currency" class="form-control">
            <option disabled>Select Currency</option>
            <option>Choose Currency</option>
            <option *ngFor="let currency of currencies">{{currency.name}}</option>
        </select>

    </div>

    <div class="col">
        <div formGroupName="address">
            <h2>Address</h2>
            <label for="street">Street:</label>
            <input formControlName="street" id="street" type="text" class="form-control" style="width: auto;">
            <div *ngIf="f['street'].touched && f['street'].invalid" class="alert alert-danger">
                Street is
                required.
                <div *ngIf="f['street'].errors && f['street'].errors['required']">Street is
                    required.</div>
            </div>
            <label for="city">City:</label>
            <input formControlName="city" id="city" type="text" class="form-control" style="width: auto;">
            <div *ngIf="f['city'].touched && f['city'].invalid" class="alert alert-danger">
                City is required.
                <div *ngIf="f['city'].errors && f['city'].errors['required']">City is required.
                </div>
            </div>
            <label for="zipCode">ZipCode:</label>
            <input formControlName="zipCode" id="zipCode" type="text" class="form-control" style="width: auto;">
            <div *ngIf="f['zipCode'].touched && f['zipCode'].invalid" class="alert alert-danger">
                ZipCode is required.
                <div *ngIf="f['zipCode'].errors && f['zipCode'].errors['required']">ZipCode is
                    required.</div>
            </div>

            <label for="country">Country:</label>
            <input formControlName="country" id="country" type="text" class="form-control" style="width: auto;">
            <div *ngIf="f['country'].touched && f['country'].invalid" class="alert alert-danger">
                Country is required.
                <div *ngIf="f['country'].errors && f['country'].errors['required']">Country is
                    required.</div>
            </div>

        </div>
    </div>
</div>
<div class="col">
<button class="btn btn-primary" type="submit" [disabled]="!form.valid">Submit</button>

我的下拉列表当我在formGroupName中有验证器=“地址”中的验证器时,是否有空白

会打破下拉列表:

<div *ngIf="f['street'].touched && f['street'].invalid" class="alert alert-danger">
                Street is
                required.
                <div *ngIf="f['street'].errors && f['street'].errors['required']">Street is
                    required.</div>
            </div>

有人建议如何修复它,以便我可以在每个控件上都有验证器?

I have spent last couple of hours to populate dropdown in my form in angular 13, and finally I have managed to make it work, although it wasnt problem in code to populate dropdown it is other controls that break my dropdown:

For example:

@Component({
  selector: 'app-company-add',
  templateUrl: './company-add.component.html',
  styleUrls: ['./company-add.component.css']
})
export class CompanyAddComponent implements OnInit {

 currencies: Currency[] = [];

  form = new FormGroup({
    name: new FormControl('',[Validators.required]),     
    currency: new FormControl('', Validators.required),
    address: new FormGroup({
        street: new FormControl('',[Validators.required]),
        city: new FormControl('',[Validators.required]),
        country: new FormControl('',[Validators.required]),
    })
  });


  constructor( public companyService: CompanyService, public currencyService: CurrencyService,
    private router: Router) {

     }

  ngOnInit() {
    this.currencyService.getAll().subscribe((data: Currency[])=>{
      this.currencies = data;
      console.log(this.currencies);    
    })  
}

  get f(){
    return this.form.controls;
  }
  
  submit(){
    console.log(this.form.value);
    this.companyService.create(this.form.value).subscribe((res:any) => {
      console.log(res);
         console.log('Post created successfully!');
         this.router.navigateByUrl('details');
    })
  }
}

<form [formGroup]="form" (ngSubmit)="submit()">
<div class="row">

    <div class="col">
        <h2>Add new company</h2>
        <label for="name">Name:</label>
        <input formControlName="name" id="name" type="text" class="form-control" style="width: auto;">
        <div *ngIf="f['name'].touched && f['name'].invalid" class="alert alert-danger">Name is requiered.
            <div *ngIf="f['name'].errors && f['name'].errors['required']">Name is requiered.</div>
        </div>          

        <label for="currency">Currency:</label>
        <select formControlName="currency" class="form-control">
            <option disabled>Select Currency</option>
            <option>Choose Currency</option>
            <option *ngFor="let currency of currencies">{{currency.name}}</option>
        </select>

    </div>

    <div class="col">
        <div formGroupName="address">
            <h2>Address</h2>
            <label for="street">Street:</label>
            <input formControlName="street" id="street" type="text" class="form-control" style="width: auto;">
            <div *ngIf="f['street'].touched && f['street'].invalid" class="alert alert-danger">
                Street is
                required.
                <div *ngIf="f['street'].errors && f['street'].errors['required']">Street is
                    required.</div>
            </div>
            <label for="city">City:</label>
            <input formControlName="city" id="city" type="text" class="form-control" style="width: auto;">
            <div *ngIf="f['city'].touched && f['city'].invalid" class="alert alert-danger">
                City is required.
                <div *ngIf="f['city'].errors && f['city'].errors['required']">City is required.
                </div>
            </div>
            <label for="zipCode">ZipCode:</label>
            <input formControlName="zipCode" id="zipCode" type="text" class="form-control" style="width: auto;">
            <div *ngIf="f['zipCode'].touched && f['zipCode'].invalid" class="alert alert-danger">
                ZipCode is required.
                <div *ngIf="f['zipCode'].errors && f['zipCode'].errors['required']">ZipCode is
                    required.</div>
            </div>

            <label for="country">Country:</label>
            <input formControlName="country" id="country" type="text" class="form-control" style="width: auto;">
            <div *ngIf="f['country'].touched && f['country'].invalid" class="alert alert-danger">
                Country is required.
                <div *ngIf="f['country'].errors && f['country'].errors['required']">Country is
                    required.</div>
            </div>

        </div>
    </div>
</div>
<div class="col">
<button class="btn btn-primary" type="submit" [disabled]="!form.valid">Submit</button>

My dropdown is blank when I have validators in my formGroupName= "address"

This breaks the dropdown:

<div *ngIf="f['street'].touched && f['street'].invalid" class="alert alert-danger">
                Street is
                required.
                <div *ngIf="f['street'].errors && f['street'].errors['required']">Street is
                    required.</div>
            </div>

Anyone has suggestion how to fix it so I can have validators on every control?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

虐人心 2025-02-19 15:26:58

在您的示例中,f ['Street']是无效的路径,因为街道不是form> form的直接后代。正确的表示法是f ['adversion']。控件['sweet']

为了进一步改进,我建议您删除get f(),只需使用indend-in-in getter 访问表单控件。这将允许您轻松访问嵌套控件,例如form.get('resplast.street')或 form.get('resplove.city') 。

In your example, f['street'] is an invalid path, because street is not a direct descendant of form. The correct notation is f['address'].controls['street'].

To further improve, I would advise you drop the get f() and just use the built-in getter to access form controls. This will allow you to easily access nested controls, in your case for example form.get('address.street') or form.get('address.city').

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文