angular - FormGroup 中的 Material 自动完成 - typescript

标签 angular forms typescript autocomplete angular-material

在我的项目中,我想对国家/地区使用 Material 自动完成功能。国家从我这里得到一切。我能够显示所有状态,但我想要的是选择要发送 ws 的状态。所以,我想把它放在formgroup中。

组件.html

<form [formGroup]="registerUserForm" (ngSubmit)="onRegisterUser()" class="col s12" materialize>

  <div class="row">
    <div class="input-field col s12">
      <input formControlName="username" id="username" type="text" class="validate" placeholder="Enter Username" minlength="3" maxlength="20"
        required="" [ngClass]="{invalid: invalidInputs}">
    </div>
  </div>

  <div class="row">
    <div class="input-field col s12">
      <input formControlName="email" id="email" type="email" class="validate" placeholder="Enter Email" required="" aria-required="true"
        [ngClass]="{invalid: invalidInputs}">
    </div>
  </div>

  <!-- Autocomplete Country Material-->

  <input formControlName="country_id" id="country_id" matInput placeholder="Select Country" aria-label="State" [matAutocomplete]="auto"
    autoActiveFirstOption [formControl]="myControlCountry">
  <mat-autocomplete #auto="matAutocomplete">
    <mat-option *ngFor="let country of filteredOptionsCountry | async" [value]="country.name">
      {{ country.name }}
    </mat-option>
  </mat-autocomplete>

 <!-- End Autocomplete Country -->


  <div id="register_user_button_container" class="row">
    <button id="register_user_button" type="submit" class="btn waves-effect waves-light">
      Register
    </button>
    <button id="cancel_button" (click)="onCancel()" class="btn waves-effect waves-light grey lighten-4 black-text">
      Cancel
    </button>
  </div>
</form>

组件.ts

导出类AddUserFormComponent实现OnInit { 国家/地区:国家/地区[];

  registerUserForm: FormGroup;


  filteredOptionsCountry: Observable<Country[]>;
  myControlCountry: FormControl = new FormControl();



  constructor(private fb: FormBuilder,
    private router: Router,

    private cs: CountryService) 
{

    this.registerUserForm = new FormGroup({
      'username': new FormControl(),
      'email': new FormControl(),
      'country_id': new FormControl(),
    });

  }

  ngOnInit() {

    this.registerUserForm = this.fb.group({
      'username': ['', Validators.compose([Validators.required, Validators.minLength(5)])],
      'country_id': ['', Validators.required],
      'email': ['', [Validators.required, ValidationService.emailValidation]],
    });

    this.filteredOptionsCountry = this.myControlCountry.valueChanges.pipe(
      startWith(''),
      map(val => this.filterCountry(val))
    );

    this.cs.getAllCountry().subscribe(
      countryes => {
        this.countryes = countryes.map((country) => {
          return new Country(country);
        });
      }
    );

  }

  onRegisterUser() {
    this.loading = true;
    this.invalidInputs = true;

    let newUser = new User(
      this.registerUserForm.value
    );

    this.userService.createUser(newUser).subscribe(
    );
  }

  onCancel() {
    this.router.navigate(['/main/users']);
  }


  //Country

  filterCountry(val: string): Country[] {
    if (val) {
      let filterValue = val.toLowerCase();
      console.log(this.countryes)
      return this.countryes.filter(country => country.name.toLowerCase().startsWith(filterValue));
    }

    return this.countryes;
  }

}

在 html 代码中,我还使用 formControlName="country_id"id="country_id"但没有任何作用。更重要的是,我使用 ReactiveFormsModule。你能给我建议任何解决方案吗?谢谢!

最佳答案

我们可以使用“controls”从表单组中获取formControName的值

解决方案:

HTML 代码:

<form [formGroup]="SearchForm">
<mat-form-field fxFlex="14" appearance="outline">
    <mat-label>Number</mat-label>
    <input type="text"
           aria-label="Number"
           matInput
           formControlName="numberName"
           [matAutocomplete]="auto">
    <mat-autocomplete #auto="matAutocomplete">
      <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
        {{option}}
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>

ts代码:

SearchForm = new FormGroup
({
numberName: new FormControl(''),
numers: new FormControl('')
}); 
Options: string[] = ['One', 'Two', 'Three'];
filteredOptions: Observable<string[]>;

constructor(){}
ngOnInit(){
this.onValueChanged();
}

public onValueChanged(){
this.filteredOptions = this.SearchForm.controls.numberName.valueChanges.pipe(
startWith(''),
map((value:any) => this._filter(value)));
}

private _filter(value: string): string[]{
const filterValue = value.toLowerCase();
return this.Options.filter(option => option.toLowerCase().includes(filterValue));
}

关于angular - FormGroup 中的 Material 自动完成 - typescript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48703606/

相关文章:

html - 如何根据 Angular 7 中 [ngStyle] 的值在 1 个单元格 <td></td> 中划分背景?

javascript - Angular 中如何实现多线程?

javascript - 仅更改或转换标签文本,而不更改表单中的值

entity-framework - 保存时忽略可选列

reactjs - 第 0 行 : Parsing error: Cannot read property 'map' of undefined"- TypeScript Custom Hook

angular - 如何使用 karma+jasmine 测试 Angular 2 中的位置

html - 使用 CSS 布局表单,使表单居中但左对齐可变宽度字段和右对齐按钮

angular - 密码验证在 Angular 5 中不起作用

typescript - StencilJS Prop 未填充在 JSX 中

javascript - 在 Angular2 应用程序中使用字符串插值从数组中提取值