标签: angular-reactive-forms

使原始的角形控件变脏

Angular 4中有一个反应形式,某些控制应该在某个时刻以编程方式设置.

this.form = formBuilder.group({
  foo: ''
});
...
this.form.controls.foo.setValue('foo');
Run Code Online (Sandbox Code Playgroud)

如何控制原始/脏状态?目前我正在使用两者form和foo原始状态,例如:

<form [formGroup]="form">
  <input [formControl]="form.controls.foo">
</form>

<p *ngIf="form.controls.foo.pristine">
  {{ form.controls.foo.errors | json }}
</p>

<button [disabled]="form.pristine">Submit</button>
Run Code Online (Sandbox Code Playgroud)

如果pristine/dirty应该只指定人工交互并且不能以编程方式进行更改,那么这里有什么解决方案?

javascript typescript angular angular-reactive-forms

8
推荐指数
1
解决办法
2万
查看次数

Angular 4获取Select控件的Selected选项文本

我想在Angular 4中获取Select控件的选择文本选项.

HTML:

<div class="col-sm-6 form-group">
<label>Industry</label>
<select   class="form-control select"  formControlName="Industry">
<option value="">Please select Value</option>  
<option *ngFor="let industry of industries"  
[ngValue]="industry.ID">{{industry.Name}}  
</option>  
</select> 
</div>


upload.component.ts
this.form.controls['Industry'].valueChanges.subscribe((name) => {
                this.form.controls['IndustryName'].setValue(name);
  });
Run Code Online (Sandbox Code Playgroud)

我正在使用Reactive的formControlName属性.

请建议回顾选定文本选择控件

angular angular-reactive-forms

8
推荐指数
4
解决办法
3万
查看次数

Reactive Angular表单等待提交时异步验证器完成

我正在构建一个反应式角形式,我正试图找到一种方法来触发提交时的所有验证器.如果验证者是同步的,那就没关系,因为我可以获得内联的状态.否则,如果验证器是异步验证器并且尚未触发验证器,则表单上的ngSubmit方法将处于挂起状态.我试图注册一个表单statusChange属性的订阅,但是当我通过markAsTouched函数调用manualy进行验证时它没有被触发.

这是一些片段:

   //initialization of form and watching for statusChanges
   ngOnInit() {
        this.ctrlForm = new FormGroup({
            'nome': new FormControl('', Validators.required),
            'razao_social': new FormControl('', [], CustomValidators.uniqueName),
            'cnpj': new FormControl('', CustomValidators.cnpj),
        });

        this.ctrlForm.statusChanges.subscribe(
            x => console.log('Observer got a next value: ' + x),
            err => console.error('Observer got an error: ' + err),
            () => console.log('Observer got a complete notification')
        )
    }
    //called on ngSubmit
    register(ctrlForm: NgForm) {
            Forms.validateAllFormFields(this.ctrlForm);
            console.log(ctrlForm.pending); 
            //above will be true if the async validator …
Run Code Online (Sandbox Code Playgroud)

javascript angular-validation angular angular-reactive-forms

8
推荐指数
3
解决办法
6331
查看次数

FormControl布尔值,在角度2中没有默认值

我在角度2(4.1.2)中使用反应形式

我有一个布尔属性,我不想有一个默认值,但它应该是必需的.

这就是我创建表单的方式:

constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
        payedOvertime: [false, Validators.required],
    });
}
Run Code Online (Sandbox Code Playgroud)

而我的HTML:

<div class="form-group">
    <label>Payed overtime</label>
    <label>
        <input type="radio" name="payedOvertime" formControlName="payedOvertime" [value]="true" />Yes
    </label>
    <label>
        <input type="radio" name="payedOvertime" formControlName="payedOvertime" [value]="false" />No
    </label>
</div>
Run Code Online (Sandbox Code Playgroud)

问题在于,虽然这可以预先选择无线电按钮,但我不想这样,而是必须通过单击其中一个无线电按钮来选择它.如果没有单击任何单选按钮,我希望表单无效.

javascript angular-validation angular angular-reactive-forms

7
推荐指数
2
解决办法
1万
查看次数

Angular - formGroupName 值更改不会更新表单

如标题所述,formGroupName值更改不会更新表单。(点击按钮后,输入中显示的值保持不变)

这是一个plunker。

@Component({
  selector: 'my-app',
  template: `
   <form [formGroup]="myForm">
    <div [formGroupName]="fgn">
        <input [formControlName]="'name'">
    </div>
</form>

<button (click)="formChange()" >Change</button>

{{fgn}}
<br>
{{myForm.value | json}}
  `,
})
export class App {

    private myForm: FormGroup;
    private fgn: String;

    ngOnInit() {
        this.fgn = 'zero';

        this.myForm = this.formBuilder.group({
            zero: this.formBuilder.group({
                name: 'Zero'
            }),
            one: this.formBuilder.group({
                name: 'One'
            })
        });
    }

    formChange() {
        this.fgn = 'one';
    }

    constructor(private formBuilder: FormBuilder) {

    }
}
Run Code Online (Sandbox Code Playgroud)

angular angular-reactive-forms

7
推荐指数
1
解决办法
2万
查看次数

如何清除 Angular Reactive Forms 中的 FormArray

我正在重置表格。它重置整个表单,但 FormArray 除外。

创建表单并在其中声明 formArray

createForm(){
    this.invoiceForm = this.formBuilder.group({
      'name': ['', Validators.required],
      'gst': [''],
      'currency': [''],
      'addressLine1': ['', Validators.required],
      'addressLine2': [''],
      'city': ['', Validators.required],
      'state': ['', Validators.required],
      'country': ['', Validators.required],
      'postalCode': ['', Validators.required],
      'email': ['', [Validators.required, Validators.email]],
      'invoiceparticulars': this.formBuilder.array([]),
      'isGstshidden' : true
    });

  }
Run Code Online (Sandbox Code Playgroud)

尝试通过重置数据来修改传入数据中表单的详细信息,即使我调用了 reset() 函数 formArray 保留其中以前的条目。

 modifyInvoice(index){

   this.invoiceForm.reset();

   let modifyData = this.modifyInvoiceArray[index];
   console.log(modifyData);

   this.invoiceNumber = modifyData.invoiceNumber;
   this.invoiceForm.patchValue({name: modifyData.address.Name});
   this.invoiceForm.patchValue({email: modifyData.email});
   this.invoiceForm.patchValue({gst: modifyData.GSTnumber});
   this.invoiceForm.patchValue({addressLine1: modifyData.address.AddressLine1});
   this.invoiceForm.patchValue({addressLine2: modifyData.address.AddressLine2});
   this.invoiceForm.patchValue({city: modifyData.address.City});
   this.invoiceForm.patchValue({country: modifyData.address.Country});
   this.invoiceForm.patchValue({postalCode: modifyData.address.PostalCode});
   this.invoiceForm.patchValue({state: modifyData.address.State});
   console.log(modifyData['particulars']);
}
Run Code Online (Sandbox Code Playgroud)

angular2-formbuilder angular-reactive-forms

7
推荐指数
2
解决办法
1万
查看次数

带有空对象的补丁值

我正在使用 Angular 6 并且我正在尝试执行 patchValue 以使用来自可观察的 http 调用的数据填充我的表单。一切都很好,除了我有一个 secondaryPhone 值,该值可以是 null 填充可观察对象的 json。当它为空时,我收到错误“无法将未定义或空值转换为对象”。我知道如果每个值不为空,我可以单独手动修补它,但是有没有办法加载这个值而不必手动修补每个值?

模型.ts

export class UserInfoModel {
    userId: number;
    dob: Date;
    firstName: string;
    middleInitial: string;
    lastName: string;
    genderTypeId: number;
    ssnLast4: string;
    userAddresses: UserAddress[];
    primaryPhone?: Phone;
    secondaryPhone?: Phone;
    fax?: Phone;
}

export class Address {
    address1: string;
    address2: string;
    city: string;
    stateCd: string;
    zipCode: string;
    internationalAddress: string;
    countryId: number;
}

export class UserAddress {
    userAddressId: number;
    userId: number;
    active: boolean;
    address: Address;
}

export class Phone {
    phoneId: number;
    phoneTypeId: …
Run Code Online (Sandbox Code Playgroud)

typescript angular angular-reactive-forms angular-observable angular6

7
推荐指数
2
解决办法
7717
查看次数

PrimeNg ui-float-label 在反应形式 patchValue() 后不浮动

我有用于创建和编辑操作的反应式表单。对于编辑,我只是在表单上,​​就像一个魅力,但来自 PrimeNg InputText 组件的浮动标签没有注意到有值填充。当我单击其中一个输入然后对其进行模糊处理时,每个输入都会更新视图并且所有标签都在顶部。patchValue(data)

在此处输入图片说明 在此处输入图片说明

我已经尝试过更改检测(视图组件将其设置为OnPush), markAsDirty(),markAllAsTouched()即使标签仍然在输入值上。不知道如何在其中一个控件上触发类似于物理模糊的 smth(不想在代码中触发它,@ViewChild()因为它对我来说看起来是错误的解决方案。

任何想法如何解决这一问题?

primeng reactive-forms angular angular-reactive-forms

7
推荐指数
1
解决办法
548
查看次数

检查是否需要 NgControl

由于各种原因,我有几个包装 PrimeNG 组件的自定义组件。我的组件的某些实例以反应形式使用,并且该字段的“要求”是使用Validators.required验证器设置的。

PrimeNG 组件提供一个required属性。

如何检查组件的 NgControl 是否有所需的验证器?存在.disabled和.invalid,但.invalid可以表示任何意思。

这是我现在使用的,它适用于下拉菜单,但对于任何其他类型的输入来说都是不正确的。

@Component({
  selector: 'my-component',
  templateUrl: 'my.component.html'
})
export class MyComponent implements OnInit, ControlValueAccessor {
  
  @Input()
  public disabled: boolean
  @Input()
  public required: boolean

  constructor(
        @Optional() @Self() public ngControl: NgControl
  ) {
        if (this.ngControl != null) {
            this.ngControl.valueAccessor = this;
        }
    }

    ngOnInit() {
        if (this.ngControl) {
            this.required = this.ngControl.invalid;
            this.disabled = this.ngControl.disabled;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我确信有更好的方法可以做到这一点,但我不知道如何做。

primeng angular angular-reactive-forms angular-forms

7
推荐指数
1
解决办法
4253
查看次数

如何使用多层嵌套 json 值修补反应式表单

我正在使用包含 formArray、formGroups 和 formControls 的多重嵌套(无限级)反应表单的值。哪个存储在数据库中。

目前,我正在使用递归函数修补表单,该函数循环遍历整个 JSON,并根据键和值创建 formArrays、formGroups 和 formControls。

现在的问题是,我使用的这种方法从性能角度来看并不好,那么有没有更好的方法来一次性修补这种多重嵌套形式呢?(只需创建表单,无需以 HTML 形式显示)

这是供问题参考的简化 JSON -

任何部分都可以有子部分,然后子部分可以有某种类型的部分

const formDataSections = [
  {
    index: 1,
    sectionName: "",
    subSections: [
      {
        index: 1,
        subSectionName: "",
        sections: [
          {
            index: null,
            sectionName: "",
            subSections: [
              {
                index: null,
                subSectionName: "",
                sections: [
                  {
                    index: null,
                    sectionName: "",
                  },
                  {
                    index: null,
                    sectionName: "",
                    subSections: [
                      {
                        index: null,
                        subSectionName: "",
                        sections: [
                          {
                            index: null,
                            sectionName: "",
                          },
                          {
                            index: null,
                            sectionName: "", …
Run Code Online (Sandbox Code Playgroud)

javascript angular angular-reactive-forms

7
推荐指数
1
解决办法
422
查看次数