【问题标题】:Angular get value from dynamically generated mat select角度从动态生成的垫选择中获取价值
【发布时间】:2022-01-27 13:24:49
【问题描述】:

我正在使用 Angular 材料制作如下所示的反应形式:

Form

使用这段代码,我做了一个动态生成的 mat select 和一个输入,但我不知道如何从所有这些中获取值。

HTML:

<div *ngFor="let number of [].constructor(cantConsumibles)">
    <mat-select placeholder="Selecciona un consumible" class="form-control" 
                formControlName="consumibles">
        <mat-option *ngFor="let consumible of consumibles" [value]="consumible">
            {{consumible.CodConsumible}}
        </mat-option>
    </mat-select>
    <input matInput type="number" formControlName="consumibles" placeholder="Cantidad">
</div>

<div align="end">
    <button mat-button (click)="agregarConsumible(true)"><mat-icon>add</mat-icon></button>
    <button mat-button (click)="agregarConsumible(false)"><mat-icon>remove</mat-icon></button>
</div>

TS:

cantConsumibles: number = 0;

   agregarConsumible(flag: boolean): void {
   (flag) ? this.cantConsumibles++ : this.cantConsumibles--;
 }

有什么想法吗?提前致谢

【问题讨论】:

    标签: html angular typescript angular-material


    【解决方案1】:

    选择 API 文档说我们可以使用 @Output() selectionChange: EventEmitter&lt;C&gt; https://material.angular.io/components/select/api 注册更改

    所以让我们在我们的选择中添加该方法以了解选择了什么。

    <mat-select placeholder="Favorite food" (selectionChange)="onFoodSelection($event)">
        <mat-option *ngFor="let food of foods" [value]="food.value">
           {{ food.viewValue }}
        </mat-option>
      </mat-select>
    

    然后我们控制台记录事件值,同时将事件值保存到变量中以备后用。

    @Component({
      selector: 'material-app',
      templateUrl: 'app.component.html'
    })
    export class AppComponent {
      output: any;
    
      foods = [
        {value: 'product10', viewValue: 'Steak'},
        {value: 'product20', viewValue: 'Pizza'},
        {value: 'product30', viewValue: 'Tacos'},
        {value: 'product40', viewValue: 'Lasagne'},
      ];
    
    
      onFoodSelection(event:any) {
        this.output = event.value;
        console.log(event.value)
      }
    }
    

    在其他元素(选择、输入、复选框等)上遵循相同的原则,获取模板更改事件并在 typescript 代码部分中执行某些操作。

    这里有一个小例子:https://stackblitz.com/edit/material-select-change-event-binding-tta13p?file=app%2Fapp.component.ts

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-15
      • 1970-01-01
      • 2020-06-24
      • 2018-05-21
      • 2016-11-09
      • 2016-01-05
      • 1970-01-01
      • 2019-05-27
      相关资源
      最近更新 更多