Ask*_*_SO 2 typescript angular-material angular
在角材料形式中,我有一个带有 mat-option 的字段,其中包含选项列表(即 a、b、c、d、e)。当用户选择/取消选择一个特定选项(即 c)时,我需要进行一些操作。但是我收到未定义的错误,即使我选择了一个选项 'c' 而没有选择任何其他选项。
我可以理解这是由于我使用的索引值[2]。我不确定如何确定用户是否选择了选项“C”,因为它的索引值可能会根据用户选择动态增加或减少。
响应数组可能如下所示:
value = {'d','c'} or value = {'c','b','a'} or value = {}
if(value[2] === 'c') {
console.log('c');
}
Run Code Online (Sandbox Code Playgroud)
有人可以帮我写打字稿代码吗?
也许您的代码中缺少一些东西。由于您告诉我们您使用mat-option,我尝试使用它创建示例代码。
组件.html
<h4>mat select</h4>
<mat-form-field>
<mat-label>Choose option</mat-label>
<mat-select [formControl]="optionControl" required (valueChange)="onChange($event)">
<mat-option>--</mat-option>
<mat-option *ngFor="let option of options" [value]="option">
{{option}}
</mat-option>
</mat-select>
</mat-form-field>
<div>
<p>Selected value</p>
{{ optionControl.value }}
</div>
Run Code Online (Sandbox Code Playgroud)
组件.ts
import {Component} from '@angular/core';
import {FormControl, Validators} from '@angular/forms';
@Component({
selector: 'app-example',
templateUrl: 'app-example.html',
styleUrls: ['app-example.css'],
})
export class AppExampleComponent {
optionControl = new FormControl('', Validators.required);
options = ['a', 'b', 'c']; // this is static but should be dynamic for your case
onChange(value: string) { // value will be selected option
if (value === 'c') {
console.log('c');
}
}
}
Run Code Online (Sandbox Code Playgroud)
看一下StackBlitz上的动作
| 归档时间: |
|
| 查看次数: |
760 次 |
| 最近记录: |