无法从 formcontrol angular 6 获取值

Not able to get a value from formcontrol angular 6

我正在尝试从 angular 表单组中获取值。

当我使用 formControlName 时,我可以获取该值,但是当我使用 [formControl] 时,我无法读取该值。

我正在使用 [formControl],因为我需要为输入字段自动完成。这是我的代码

HTML:

  <form class="form-horizontal" novalidate autocomplete="off" (ngSubmit)="searchTransaction()" [formGroup]="searchForm">

  <mat-form-field *ngIf="searchForm.get('searchType').value==2" class="example-full-width">
            <input matInput placeholder="Integrated Client"  [formControl] = "Client"  [matAutocomplete]="auto">
            <mat-autocomplete #auto="matAutocomplete">
                <mat-option *ngFor="let option of clientfilteredOptions | async" [value]="option">
                  {{option}}
                </mat-option>
              </mat-autocomplete>                  
        </mat-form-field>   

打字稿:

export class TransactionSearchComponent implements OnInit{
constructor(private fb:FormBuilder,private transactionService:TransactionService, private LoginvalidationService:LoginvalidationService, private ExcelService:ExcelService){   }
searchForm:FormGroup;
Client = new FormControl();

ngOnInit(): void {

        this.searchForm=this.fb.group({
                     client:[''],
                 })

       this.clientfilteredOptions = this.Client.valueChanges
        .pipe(
        startWith(''),
        map(value => this._Clientsfilter(value))      
      );
    }
 private _Clientsfilter(value: string): string[] {
        const filterValue = value.toLowerCase();  

        return this.clients.filter(option => option.toLowerCase().includes(filterValue));
    }

  searchTransaction(){ 
console.log(this.searchForm.get('client').value);
}

请检查 html Client 与用法 client

中的大小写

我建议在使用表单组时不要使用 *ngIf,而是使用 ngStyle 或 ngClass 或 [hidden] 与 属性 绑定。

* forControlName 背后的原因不适用于 ngIf - ngIf 从 html 中完全删除或添加块,这就是为什么在 ngIf 之外无法访问变量的原因。

下面是带有隐藏属性的 formControlName 的工作代码,

app.component.html

<button (click)="toggle()"> Toggle LastName of FormControl </button>

<div >
  <form [formGroup]="fieldFormGroup">
    <input type="text" formControlName="firstName" /> <br /><br />
  <input type="text" formControlName="lastName" [hidden]="showBlock" /> 
  </form>
</div>

<div>
   {{fieldFormGroup.value | json}}
</div>

<input type="text" formControlName="lastName" [style.display]="showBlock ? 'inherit' : 'none'" />

<style>
    .hide {
        display: none;
    }

    .show {
        display: block;
    }
</style>
<input type="text" formControlName="lastName" [ngClass]="showBlock ? 'show' : 'hide'" />

app.component.ts

从“@angular/core”导入{组件};

import { FormGroup, FormBuilder } from "@angular/forms";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  public showBlock: boolean = true;
  public fieldFormGroup: FormGroup;

  constructor(private fb: FormBuilder) {
    this.fieldFormGroup = this.fb.group({
      firstName: ["pravin"],
      lastName: ["patil"]
    });
  }

  public toggle() {
    this.showBlock = !this.showBlock;
  }
}

以防万一,您需要将 formControl 添加到 fromGroup

有两种方法,

this.searchForm=this.fb.group({
    client:this.client
})

或者你可以在方法中添加控件。例如:

searchTransaction(){ 
    this.searchForm.addControl('client',this.client);
    console.log(this.searchForm.value);
}

最好保持相同的大小写(小写 | 大写 | 任何首选大小写),这样在您编写长代码时不会让您感到困惑

您不需要像这样定义表单控件:

Client = new FormControl();

只需使用:

this.searchForm=this.fb.group({
                 client:[''],
             })
this.searchForm.controls.get("client").valueChanges.subscribe((value)=>{
      //Do something
});

并且视图使用:

formControlName="client" // small one