【问题标题】:Not able to get a value from formcontrol angular 6无法从 formcontrol angular 6 中获取值
【发布时间】:2019-11-10 18:50:40
【问题描述】:

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

当我使用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);
}

【问题讨论】:

    标签: angular typescript angular6 form-control


    【解决方案1】:

    我建议在处理表单组时不要使用 *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;
      }
    }
    

    【讨论】:

      【解决方案2】:

      如果您需要将formControl 添加到fromGroup

      有两种方法,

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

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

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

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

      【讨论】:

        【解决方案3】:

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

        Client = new FormControl();
        

        只需使用:

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

        对于视图使用:

        formControlName="client" // small one
        

        【讨论】:

        • this.form 替换为this.searchForm Lil 错字
        【解决方案4】:

        请检查 html Client 与用法client 中的大小写

        【讨论】:

        • 没有,即使更改了大小写也不起作用
        猜你喜欢
        • 2019-03-28
        • 2019-04-27
        • 1970-01-01
        • 2019-03-13
        • 1970-01-01
        • 2019-03-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多