如何使用angular4将选定的选项值发布到角度材质表

时间:2018-05-24 07:01:22

标签: angular angular-material-5

  

您好我希望将所选值发布到角度材质表中,但即使我选择了值,它也显示为空,如图所示。   当我选择状态并输入城市名称时,这些值应该出现在表格中但是所选择的值没有绑定到表格中请帮帮我   提前致谢

Image1

Image2

  

Component.html

      <div class="form">        
    <mat-form-field>
      <mat-select placeholder="--Select State--" [(ngModel)]="selectedState" name="state">
        <mat-option>None</mat-option>
        <mat-option *ngFor="let state of stateRows" [value]="state" [(ngModel)]='statName' name="state"  #stateName>{{state.stateName}}</mat-option>
      </mat-select>
    </mat-form-field>  
  </div><br><br>

  <div class="form">
    <mat-form-field color="accent">
      <input matInput #inputstate class="form-control" [(ngModel)]='citName' #cityName placeholder="City Name" name="cityName" required >
      <mat-error *ngIf="formControl.invalid">{{getErrorMessage()}}</mat-error>              
    </mat-form-field>
  </div><br><br> 

</form>
    <div mat-dialog-actions  align="end">
        <button mat-raised-button [type]="submit" color="accent" [mat-dialog-close]="1" (click)="saveCity()">Save</button>
        <button mat-raised-button color="primary" (click)="onNoClick()" tabindex="-1">Cancel</button>
    </div>
  

component.ts

export class AddCityDialogComponent {

formControl = new FormControl('', [
Validators.required
// Validators.email,
 ]);

 public cityObj: any = [{ stateName: '', cityName: '' }];
 stateName: string[];
 cityName: string;
 citName: string;
 statName:string;
 selectedDay: string = '';

selectChangeHandler (event: any) {
//update the ui
this.selectedDay = event.target.value;
 }

 states: any[];
 city: string[];
// stateName: string[];
 selected = null; 
 stateRows:any[];

 constructor(public dialogRef: MatDialogRef<AddCityDialogComponent>,
          @Inject(MAT_DIALOG_DATA)
          private http: HttpClient, private stateservice:StateService) {   }

ngOnInit(){
  this.stateservice.getCityTableData()
  .subscribe(states =>{
      this.stateRows=states;
      console.log(states);
    });
   }

 saveCity(stateName: string, cityName: string): void {
  const data = { 'stateName': this.statName, 'cityName': this.citName };
 const d = JSON.stringify(data);        
 this.stateservice.addNewCity(d).subscribe(res => { });  
 }

1 个答案:

答案 0 :(得分:0)

即使您正在this.stateservice.addNewCity(d)方法中发布数据,但是您是否再次从服务中获取数据,因为您使用ngOnInit()方法获取数据并在发布数据后不会在给定代码中再次填充表数据。

saveCity()方法可以是这样的 -

saveCity(stateName: string, cityName: string): void {
  const data = { 'stateName': this.statName, 'cityName': this.citName };
  const d = JSON.stringify(data);        
  this.stateservice.addNewCity(d).subscribe(res => { });  

  this.stateservice.getCityTableData()
  .subscribe(states =>{
     this.stateRows = states;
  });
}

如果这不起作用,那么服务方法可能存在一些问题。