【问题标题】:matAutocomplete don't save value -- TypescriptmatAutocomplete 不保存价值——打字稿
【发布时间】:2018-07-26 09:18:18
【问题描述】:

我的表单不适用于自动完成输入,matAutocomplete 不保存价值——打字稿。 我不明白有什么问题。你能给我一些建议或想法吗?

我的html代码:

<form [formGroup]="Myform" (ngSubmit)="save()" 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>
    <input formControlName="country_id" id="country_id" matInput placeholder="Select Country" aria-label="State" [matAutocomplete]="auto"
      autoActiveFirstOption [formControl]="country_id">
    <mat-autocomplete #auto="matAutocomplete">
      <mat-option id="country_id" *ngFor="let country of filteredOptionsCountry | async" [value]="country.name">
        {{ country.name }}
      </mat-option>
    </mat-autocomplete> 

    <input formControlName="region_id" id="region_id" matInput placeholder="Select Region*" aria-label="State" [matAutocomplete]="auto4"
      autoActiveFirstOption [formControl]="region_id">
    <mat-autocomplete #auto4="matAutocomplete">
      <mat-option *ngFor="let region of filteredOptionsRegion | async" [value]="region.name">
        {{ region.name }}
      </mat-option>
    </mat-autocomplete>     

   <input formControlName="city" id="city" matInput placeholder="Select City*" aria-label="State" [matAutocomplete]="auto1"
      autoActiveFirstOption [formControl]="city">
    <mat-autocomplete #auto1="matAutocomplete">
      <mat-option *ngFor="let city of filteredOptionsCity | async" [value]="city.name">
        {{ city.name }}
      </mat-option>
    </mat-autocomplete> 

    <div id="register_user_button_container" class="row">
      <button id="register_user_button" type="submit" class="btn waves-effect waves-light">
        Register
      </button>

    </div>
  </form>

而我的 ts 代码是这样的:

filteredOptionsCountry: any;
  country_id: FormControl = new FormControl();

  filteredOptionsCity: any;
  city: FormControl = new FormControl('');
   filteredOptionsRegion: any;
  region_id: FormControl = new FormControl('');

  constructor(private fb: FormBuilder,
    private router: Router,
    private userService: UserService,
    private roleService: RoleService,
    private cs: CountryService,
    private rs: RegionService,
    private citys: CityService) {

    this.Myform = new FormGroup({
     'username': new FormControl(),
      'country_id': new FormControl(''),
      'city': new FormControl(''),
     'region_id': new FormControl('')
    });
  }

  ngOnInit() {

    this.filteredOptionsCountry = this.country_id.valueChanges.pipe(
      startWith(''),
      map(val => this.filterCountry(val))
    );
    this.filteredOptionsCity = this.city.valueChanges.pipe(
      startWith(''),
      map(value => this.filterCity(value))
    );
    this.filteredOptionsRegion = this.region_id.valueChanges.pipe(
      startWith(''),
      map(value => this.filterRegion(value))
    );

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

    this.rs.getAllRegion().subscribe(
      regions => {
        this.regions = regions.map((region) => {
          return new Region(region);
        });
      }
    );

    this.citys.getAllCity().subscribe(
      cityes => {
        this.cityes = cityes.map((city) => {
          return new City(city);
        });
      }
    );
  }


  filterCity(val: string): City[] {
    if (val) {
      let filterValue = val.toLowerCase();
      console.log(this.cityes)
      return this.cityes.filter(city => city.name.toLowerCase().startsWith(filterValue));
    }

    return this.cityes;
  }


  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;
  }


  filterRegion(value: string): Region[] {
    if (value) {
      let filterValueRegion = value.toLowerCase();
      return this.regions.filter(reg => reg.name.toLowerCase().startsWith(filterValueRegion));
    }
    return this.regions;
  }
  save() {

    let newUser= this.Myform.value
    console.log(newUser)

  }
}

在控制台中,自动完成输入没有显示任何内容。

请问有什么解决这个问题的建议吗?谢谢

console.log(this.MyForm)

【问题讨论】:

  • 您正在将 MatAutocomplete 绑定到 COMPONENT 的“country_id”,但您正在打印“this.Myform.value”并且“country_id”始终是新的 FormControl('')。请尝试“console.log(this.country_id);”。

标签: angular forms typescript autocomplete angular-material


【解决方案1】:

好的,首先你可以使用onSelectionChange:

&lt;mat-option (onSelectionChange)="updateForm(city.id, city)"

现在在你的组件中你想用 patchValue 更新你的表单:

private updateForm(_id: any, _formControlName: any){
  this.form['controls'][_formControlName].patchValue(_id);
}

如果事件触发两次,请执行&lt;mat-option (onSelectionChange)="updateForm($event, city.id, city)"

还有

private updateForm(_event: any, _id: any, _formControlName: any){
   if (_event.isUserInput) {
     this.form['controls'][_formControlName].patchValue(_id);
   }
}

编辑

&lt;mat-option (onSelectionChange)="updateForm(city.id, 'city')" // where your city automcomplete is

对于国家来说,它看起来像:

&lt;mat-option (onSelectionChange)="updateForm(country.id, 'country_id')"

【讨论】:

  • Cannot read property 'patchValue' of undefined--> in ts code: private updateForm(city: any, country_id: any, region_id: any, _formControlName: any) { this.Myform['controls' ][_formControlName].patchValue( { city: this.city, country_id: this.country_id, region_id: this.region_id } ) }
  • 和html代码:
  • 你能为我制作一个console.log(this.Myform)吗?然后你就可以看到控件了。
  • 你基本需要的是:this.Myform['controls']['country_id'].patchValue( SelectedCountryID)
  • SelectedCountryID 在我的代码中是什么?我设置了照片
猜你喜欢
  • 2015-10-25
  • 2019-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-16
相关资源
最近更新 更多